txt文件打开的编码错误
这一句改成f = open(file,encoding='utf-8')
完整代码import os
x = input("请将该脚本放于查找的文件夹内,请输入关键字:")
y = input("请问是否需要打印关键字(%s)在文件夹中具体位置(yes/no):" % x)
#def main1(line , x):
#list1 = []
#for t in line.find[x]:
#list1.append(t + 1)
#return list1
def main1(line , x):
list1 = []
begin = line.find(x)
while begin != -1:
list1.append(begin + 1)
begin = line.find(x , begin+1)
return list1
def main2(file , x):
f = open(file,encoding='utf-8')
p = dict() #g = dict()
count = 0
for h in f:
count +=1
if x in h:
pos = main1(h , x)
p[count] = pos #g[count] = pos
f.close()
return p #return g
def main3(p):
x = p.keys()
x = sorted(x)
for temp in x:
print("关键字出现在%s,第%s个位置;" % (temp , str(p[temp])))
def main(x , y):
all_file = os.walk(os.getcwd())
m = all_file
a = []
for i in m:
for ea in i[2]:
if os.path.splitext(ea)[1] == '.txt': #if os.path.splitext(ea)[1] == '.text'
k = os.path.join(i[0],ea)
a.append(k)
for z in a:
p = main2(z , x) #p = main3(z , x)
if p: #if p:
print("================")
print("在文件(%s)中找到关键字(%s)" % (z , x))
if y in ('yes','Yes','YES'):
print(p) # print(p)
main(x , y)
|