|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import os
def print_pos(key_dict):
key = key_dict.keys()
key = sorted(key)
for each_key in key:
print('关键词出现在第%s行的第%s格处' % (each_key,key_dict[each_key]))
def pos_in_line(line, key):
position = []
pos = line.find(key)
while pos != -1:
position.append(pos+1)
pos = line.find(key,pos+1)
return position
def search_in_file(file_name, key):
key_dict = dict()
count = 0
f = open(file_name)
for each_line in f:
count += 1
if key in each_line:
position = pos_in_line(each_line, key)
key_dict[count] = position
f.close()
return key_dict
def search_key(key,judge):
all_file = os.walk(os.getcwd())
txt_file = []
for each in all_file:
for each_file in each[2]:
if os.path.splitext(each_file)[1] == '.txt':
txt_file.append(os.path.join(each[0],each_file))
for each_txt in txt_file:
key_dict = search_in_file(each_txt, key)
if key_dict:
print('==================================================')
print('在%s里发现关键词【%s】' % (each_txt,key))
if judge in ['YES','Yes','yes']:
print_pos(key_dict)
key = input('请输入关键词:')
judge = input('请问是否打印?(YES/NO)')
search_key(key,judge)
这是封装函数之后的代码,没有问题,请看下面的
import os
def search_key(key,judge):
txt_file = []
all_file = os.walk(os.getcwd())
for each in all_file:
for each_file in each[2]:
if os.path.splitext(each_file)[1] == '.txt':
txt_file.append(os.path.join(each[0],each_file))
for each_txt in txt_file:
key_dict = dict()
count = 0
f = open(each_txt)
for each_line in f:
count += 1
if key in each_line:
pos = []
position = each_line.find(key)
while position != -1:
pos.append(position + 1)
position = each_line.find(key,position + 1)
key_dict[count] = pos
f.close()
if key_dict:
print('==================================================')
print('在%s里发现关键词%s' % (each_txt,key))
if judge in ['yes','Yes','YES']:
key = key_dict.keys()
key = sorted(key)
for each_key in key:
print('关键字出现在第%s行的第%s字符的位置' % (each_key,str(key_dict[each_key])))
key = input('请输入关键词:')
judge = input('请问是否需要打印?(YES/NO)')
search_key(key,judge)
这是没封装的代码,会报错:
Traceback (most recent call last):
File "D:\python\练习.py", line 33, in <module>
search_key(key,judge)
File "D:\python\练习.py", line 15, in search_key
if key in each_line:
TypeError: 'in <string>' requires string as left operand, not list
我看了半天没看出来有啥区别。。。
哪位大哥能给小弟解释一下
key = sorted(key)这里把字符串变成了列表,在下一回循环中执行if key in each_line:语句就会因为[列表] in '字符串' 的不成立关系而出错,在循环中要记住那些变量需要初始化
|
|