鱼C论坛

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

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

[复制链接]
发表于 2022-3-5 14:27:01 | 显示全部楼层 |阅读模式

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

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

x

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

  2. import os

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

  9. #查找关键字在某一行中的具体位置
  10. def pos_in_line(line, key):
  11.     pos = []
  12.     begin = line.find(key)
  13.     while begin != -1:
  14.         pos.append(begin + 1)  # 用户的角度是从1开始数
  15.         begin = line.find(key, begin + 1)  # 从下一个位置继续查找

  16.     return pos

  17. #查找关键字在第几行
  18. def search_in_file(file_name, key):
  19.     f = open(file_name)
  20.     count = 0  # 记录行数
  21.     key_dict = dict()  # 字典,用户存放key所在具体行数对应具体位置

  22.     for each_line in f:
  23.         count += 1
  24.         if key in each_line:
  25.             pos = pos_in_line(each_line, key)  # key在每行对应的位置
  26.             key_dict[count] = pos

  27.     f.close()
  28.     return key_dict

  29. #判断文件是否为txt文件
  30. def search_files(key, detail):
  31.     all_files = os.walk(os.getcwd())
  32.     txt_files = []

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

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


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


第41行的  for each_file in i[2]    为什么不可以换成  each_file = i[2]?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-3-5 14:34:58 | 显示全部楼层
因为 i 可能是指多个对象合成的类型,如列表,元组......
所以需要一一用 for 循环遍历出来,
但是如果你上面的代码生成出来的 i 变量的值为单个元素,如:
  1. i = 213121
复制代码

就可以直接使用:
  1. each_file = i[2]
复制代码

但保险起见,为了防止代码会出现什么不确定因素,我们还是用 for 循环安全一些!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-4-30 03:53

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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