|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
小甲鱼,30讲课后习题最后一题调用太复杂看不懂
- import os #读取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) #从下一个位置继续查找,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)
复制代码
费劲了好久加了注释,可是发现第一个函数全程没有被调用过,而且运行报错。。。 |
|