ghsydota 发表于 2020-5-2 18:01:23

python课后练习30讲 第四题

import os

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


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

    return pos


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在每行对应的位置
            key_dict = pos
   
    f.close()
    return key_dict


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

    for i in all_files:
      for each_file in i:
            if os.path.splitext(each_file) == '.txt': # 根据后缀判断是否文本文件
                each_file = os.path.join(i, each_file)
                txt_files.append(each_file)

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


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


这两句
for i in all_files:
      for each_file in i:
第两句如果是取三元组中的第三个list,然后遍历里面的元素的话
不应该是for _ in all_files:
那第一句是什么意思?
遍历3个元组?

永恒的蓝色梦想 发表于 2020-5-2 18:05:46

walk 返回迭代器,这个迭代器生成三元组

ghsydota 发表于 2020-5-2 20:36:56

永恒的蓝色梦想 发表于 2020-5-2 18:05
walk 返回迭代器,这个迭代器生成三元组

迭代器这个不是很能理解啊,比如如果返回三元组是(路径,[文件夹],[文件]),如果返回的是迭代器,显示的是什么呢

永恒的蓝色梦想 发表于 2020-5-2 20:40:43

ghsydota 发表于 2020-5-2 20:36
迭代器这个不是很能理解啊,比如如果返回三元组是(路径,[文件夹],[文件]),如果返回的是迭代器,显示的是什 ...

迭代器就是用来 for in 的东西

ghsydota 发表于 2020-5-2 20:48:11

永恒的蓝色梦想 发表于 2020-5-2 20:40
迭代器就是用来 for in 的东西

哦哦哦好的好的,谢谢
页: [1]
查看完整版本: python课后练习30讲 第四题