鱼C论坛

 找回密码
 立即注册
查看: 2220|回复: 1

30讲 第四题 好难理解,转不过来了 4个def模块啥意思

[复制链接]
发表于 2016-4-28 17:37:37 | 显示全部楼层 |阅读模式

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

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

x
突然感觉难好多啊,4个def某块  啥意思,始终绕不过来 都开始朱行翻译了


  1. import os

  2. def print_pos(key_dict):     #def 创建函数名(参数)
  3.     keys = key_dict.keys()    #返回字典中键列表 (key1:value1,key2:wallet)  键必须唯一,值不必
  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)        # find查找key 有 !=0.找不到返回-1
  10.     while begin != -1:
  11.         pos.append(begin + 1)      # 用户的角度是从1开始数,append是 在列表添加这个新元素
  12.         begin = line.find(key, begin+1)     # 从下一个位置继续查找

  13.     return pos # 返回到pos


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


  27. def search_files(key, detail):   
  28.     all_files = os.walk(os.getcwd())              #walk 返回三元组(路径目录文件名)
  29.     txt_files = []

  30.     for i in all_files:
  31.         for each_file in i[2]:
  32.             if os.path.splitext(each_file)[1] == '.txt':   # 根据后缀判断是否文本文件 split分离wen'j文件扩展
  33.                 each_file = os.path.join(i[0], each_file)    #join 将合并成路径名
  34.                 txt_files.append(each_file)

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


  42. key = input('请将该脚本放于待查找的文件夹内,请输入关键字:')
  43. detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):' % key)
  44. search_files(key, detail)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2016-4-29 22:32:34 | 显示全部楼层
顺着流程看就简单多了。
search_files(key, detail)  调用 search_in_file(each_txt_file, key)和print_pos(key_dict)。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-3-29 01:46

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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