鱼C论坛

 找回密码
 立即注册
查看: 1122|回复: 2

[已解决]pthon 第30课 最后一题 求助

[复制链接]
发表于 2018-3-13 19:34:05 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. import os

  2. def print_pos(key_dict):
  3.     keys = key_dict.keys()
  4.     keys = sorted(keys) # 由于字典是无序的,我们这里对行数进行排序
  5.     for each_key in keys:
  6.         print('关键字出现在第 %s 行,第 %s 个位置。' % (each_key, str(key_dict[each_key])))

  7. def pos_in_line(line, key):
  8.     pos = []
  9.     begin = line.find(key)
  10.     while begin != -1:
  11.         pos.append(begin + 1) # 用户的角度是从1开始数
  12.         begin = line.find(key, begin+1) # 从下一个位置继续查找
  13.         
  14.     return pos

  15. def search_in_file(file_name, key):
  16.     f = open(file_name)
  17.     count = 0 # 记录行数
  18.     key_dict = dict() # 字典,用户存放key所在具体行数对应具体位置
  19.    
  20.     for each_line in f:
  21.         count += 1
  22.         if key in each_line:
  23.             pos = pos_in_line(each_line, key) # key在每行对应的位置
  24.             key_dict[count] = pos
  25.    
  26.     f.close()
  27.     return key_dict

  28. def search_files(key, detail):   
  29.     all_files = os.walk(os.getcwd())
  30.     txt_files = []

  31.     for i in all_files:
  32.         for each_file in i[2]:
  33.             if os.path.splitext(each_file)[1] == '.txt': # 根据后缀判断是否文本文件
  34.                 each_file = os.path.join(i[0], each_file)
  35.                 txt_files.append(each_file)

  36.     for each_txt_file in txt_files:
  37.         key_dict = search_in_file(each_txt_file, key)
  38.         if key_dict:
  39.             print('================================================================')
  40.             print('在文件【%s】中找到关键字【%s】' % (each_txt_file, key))
  41.             if detail in ['YES', 'Yes', 'yes']:
  42.                 print_pos(key_dict)

  43. key = input('请将该代码放于待查找的文件夹内,请输入关键字:')
  44. detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):' % key)
  45. search_files(key, detail)
复制代码


def search_in_file(file_name, key):
    f = open(file_name)
    count = 0 # 记录行数
    key_dict = dict() # 字典,用户存放key所在具体行数对应具体位置
   
    for each_line in f:
        count += 1
        if key in each_line:
            pos = pos_in_line(each_line, key)
            key_dict[count] = pos
  #  请问 这两句红色的什么意思
   
    f.close()
    return key_dict
最佳答案
2018-3-13 21:35:58
第一句,获得读取的数据
第二句,将该数据作为count键对应的值放到字典key_dict中
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2018-3-13 21:35:58 | 显示全部楼层    本楼为最佳答案   
第一句,获得读取的数据
第二句,将该数据作为count键对应的值放到字典key_dict中
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-3-14 06:23:11 | 显示全部楼层
BngThea 发表于 2018-3-13 21:35
第一句,获得读取的数据
第二句,将该数据作为count键对应的值放到字典key_dict中

好的谢谢大神
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-19 13:45

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表