|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
参考第30课的回答,自己写了如下代码,为什么不对,(要在C:\Users\wutin\Documents\Python\Exercises下查找)
import os
def print_pos(key_dict):
keys = key_dict.keys()
keys = sort(keys)
for each_key in keys:
print('关键词在第%s行,第%s个位置' % (each_key,str(key_dict[each_key])))
def pos_in_line(line,keyword):
pos = []
begin = line.find(keyword)
while begin != -1:
pos.append(begin+1)
begin = line.finde(keyword,begin+1)
return pos
def search_in_file(file,keyword):
f = open(file,encoding='utf-8')
line_num = 0
key_dict = dict()
for each_line in file:
count += 1
if keyword in each_line:
key_dict[count] = pos_in_line(each_line,keyword)
f.close()
return key_dict
def search_files(keyword):
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':
txt_files.append(os.path.join(i[0],each_file)
for each_txt_file in txt_files:
key_dict = seach_in_file(each_txt_file,keyword)
if key_dict:
print('===========================================')
print('在文件%s中找到关键词%s' % (each_txt_file,keyword))
print_pos(key_dict)
keyword = input('请输入查找的关键词')
os.chdir('C:\Users\wutin\Documents\Python\Exercises')
search_files(keyword)
文件编码的问题,比如txt文件可以是多个编码方式。
f = open(file,encoding='utf-8')
而你上面这句代码使用'utf-8'编码打开,当文件本身不是通过utf-8编码时,就无法读取了,你可以用notepad++打开重新编码,如果是txt文件直接打开后另存时选择编码方式,再用对应编码类型读取;
例如:假设你文件编码是'gbk',你的代码就需要改成:f = open(file,encoding='gbk')
你也可以用下面的方式,获取文件的编码类型
执行
import chardet
f = open('a.doc',r)
data = f.read()
print chardet.detect(data)
结果
{'confidence': 0.64465744, 'encoding': 'utf-8'}
前面是相似度 后面是编码格式
或者 return chardet.detect(data).get("encoding") 直接获取文件编码格式
|
|