|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import os
import os.path
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)
begin = line.find(key,begin + 1)
return pos
def search_in_file(file_name,key):
f = open(file_name,encoding='UTF-8')
count = 0
key_dict = dict()
for each_line in f:
count += 1
if key in each_line:
pos = pos_in_line(each_line,key)
key_dict[count] = pos
f.close()
return key_dict
def search_file(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('========================\n')
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_file(key,detail)
求助论坛的朋友们,为什么我这段代码会出现以下的错误?
======= RESTART: C:/Users/xunqing zhang/Desktop/练习/练习28课后题/练习28课后题4答案.py =======
请输入要查找的关键字:小甲鱼
请问是否需要打印关键字【小甲鱼】在文件中的具体位置(YES/NO):yes
========================
在文件【C:\Users\xunqing zhang\Desktop\练习\练习28课后题\test.txt】中找到关键字【小甲鱼】
关键字出现在第4行,第[8, 20]个位置
关键字出现在第5行,第[7]个位置
关键字出现在第8行,第[4]个位置
Traceback (most recent call last):
File "C:/Users/xunqing zhang/Desktop/练习/练习28课后题/练习28课后题4答案.py", line 57, in <module>
search_file(key,detail)
File "C:/Users/xunqing zhang/Desktop/练习/练习28课后题/练习28课后题4答案.py", line 47, in search_file
key_dict = search_in_file(each_txt_file,key)
File "C:/Users/xunqing zhang/Desktop/练习/练习28课后题/练习28课后题4答案.py", line 26, in search_in_file
for each_line in f:
File "C:\Users\xunqing zhang\AppData\Local\Programs\Python\Python39\lib\codecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position 31: invalid start byte
谢谢大家
本帖最后由 sunrise085 于 2020-11-30 15:44 编辑
没有其他问题,就是你所打开的文件编码不正确,部分内容不是utf8编码。
你把你这个txt文件打开,另存一下,存储的时候修改一下编码就可以了
|
|