小丑9 发表于 2022-3-5 14:27:01

第41行的 for each_file in i[2] 为什么不可以换成 each_file = i[2]?


#编写一个程序,用户输入关键字,查找当前文件夹内(如果当前文件夹内包含文件夹,则进入文件夹继续搜索)所有含有该关键字的文本文件(.txt后缀),要求显示该文件所在的位置以及关键字在文件中的具体位置(第几行第几个字符)

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

#判断文件是否为txt文件
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)


第41行的for each_file in i    为什么不可以换成each_file = i?

python爱好者. 发表于 2022-3-5 14:34:58

因为 i 可能是指多个对象合成的类型,如列表,元组......
所以需要一一用 for 循环遍历出来,
但是如果你上面的代码生成出来的 i 变量的值为单个元素,如:
i = 213121
就可以直接使用:
each_file = i
但保险起见,为了防止代码会出现什么不确定因素,我们还是用 for 循环安全一些!
页: [1]
查看完整版本: 第41行的 for each_file in i[2] 为什么不可以换成 each_file = i[2]?