鱼C论坛

 找回密码
 立即注册
查看: 2325|回复: 6

python 030课 课后题 最后一题

[复制链接]
发表于 2016-12-12 08:59:02 | 显示全部楼层 |阅读模式
10鱼币
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[each_key])))
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[count] = 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[2]:
            if os.path.splitext(each_file)[1] == '.txt': # 根据后缀判断是否文本文件
                each_file = os.path.join(i[0], 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)
这课的课后题就这题看不懂,麻烦大神逐步解答一下,谢了
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-12-12 08:59:03 | 显示全部楼层
  1. import os

  2. def print_pos(key_dict):                  #定义输出函数
  3.     keys = key_dict.keys()                #将字典中的key赋值给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)                #有关键字的位置返回给begin,如不存在则返回-1
  10.     while begin != -1:                       
  11.         pos.append(begin + 1)             #若关键字存在将位置数返回到pos列表中,因为程序是从0开始计算的,所以此处应加1
  12.         begin = line.find(key, begin+1)   #然后再从begin+1的位置继续寻找关键字

  13.     return pos                            #返回返回位置列表

  14. def search_in_file(file_name,key):        #定义函数
  15.     f = open(file_name)                   #打开文件
  16.     key_dict = dict()                     #定义一个空字典key用来存放第几行出现关键字
  17.     count = 0                             #给count一个初始值
  18.    
  19.     for each_line in f:                   #遍历文件
  20.         count +=1                         #每遍历一行count数加1
  21.         if key in each_line:              #如果该行中有关键字调用pos_in_line函数
  22.             pos = pos_in_line(each_line,key)
  23.             key_dict[count] = pos         #将行数做为key,具体位置作为xalue

  24.     f.close()                             #关闭文件,返回字典
  25.     return key_dict


  26. def search_files(key,detail):             #定义函数
  27.     all_files = os.walk(os.getcwd())      #返回当前目录的所有子目录
  28.     txt_files = []                        #定义列表用于存放文件

  29.     for i in all_files:                   #遍历all_files
  30.         for each_file in i[2]:            #遍历所有包含文件
  31.             if os.path.splitext(each_file)[1] == '.txt': #如果文件是.txt文件结尾的,each_file就是当前路径加文件名
  32.                 each_file = os.path.join(i[0],each_file)
  33.                 txt_files.append(each_file)              #将文件名放到列表中

  34.         for each_txt_file in txt_files:                   #遍历文件
  35.             key_dict = search_in_file(each_txt_file,key)  #调用函数
  36.             if key_dict:                                 #如果文件中有关键字输出
  37.                 print('======================================================================')
  38.                 print('在文件【%s】中找到关键字【%s】'%(each_txt_file,key))
  39.                 if detail in ['YES','Yes','yes']:        #如果detail是YES,yes或是Yes中的任意个
  40.                     print_pos(key_dict)                  #调用输出函数

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

使用道具 举报

发表于 2016-12-12 13:20:13 | 显示全部楼层
给楼上点个赞
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-12-12 16:19:55 | 显示全部楼层

for each_file in i[2]:            #遍历所有包含文件
这句中的[2]是什么有意思
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-12-12 17:22:45 | 显示全部楼层
cuizihan2359 发表于 2016-12-12 16:19
for each_file in i[2]:            #遍历所有包含文件
这句中的[2]是什么有意思

因为os.walk()返回的是一个三元组,所以i[2]标的是第三个元祖,也就是所有的包含文件
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-12-12 17:37:07 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-12-13 07:34:42 | 显示全部楼层
小茗同学 发表于 2016-12-12 17:22
因为os.walk()返回的是一个三元组,所以i[2]标的是第三个元祖,也就是所有的包含文件

懂了,谢谢你一直陪伴我的学习,谢谢
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2026-2-24 11:43

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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