遇到的问题:
1、写完之后,发现只能运行打印结果,但是功能和自己想的不太一样,于是去学了pycharm一行一行找问题,后来发现,不是代码的问题,是自己根本没有这个关键词。但是学会了debug
13.pycharmDebug断点使用教程 (xiaohongshu.com)
2、遇到了python中TypeError问题: not enough arguments for format string这个问题
python中TypeError问题: not enough arguments for format string(已解决)_monaxu的博客-CSDN博客
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)#从下一个位置继续查找
return pos#输出结果应该是【小甲鱼在第3个位置,行数还不定】
def search_in_file(file_name,key):#找具体位置的函数
with open(file_name, encoding='utf-8') as file:
count = 0#记录行数
key_dict = dict()#字典,用户存放key所在具体行数对应具体位置
for each_line in file:#文件中的每一行
count += 1#每一行遍历一遍的话,行数都会+1
if key in each_line:
pos = pos_in_line(each_line,key)#key在每行对应的位置
key_dict[count] = pos#在出现目标关键字的行中定义该关键字出现的行数 大概是【3,4】在第三行第5个位置出现了
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)
只能说看懂,自己写,还是写不出来。但是学到一个思想,就是如果想要表达的东西太多可以,多分几个函数。
3、然后这个代码的主要思想就是
a)先写输出函数
b)再写找行中关键词位置的函数
c)再写文章中找关键词的函数
d)最后再输出