问题:在cmd中无法得出结果文件,出现错误,不知道如何改进。
题目要求:对当前文件夹(11.2countfiles.py 文件所在文件夹)下全部文件名是字母a打头的.txt文件 进行词频统计,统计的总的结果写入 "结果文件" r2.txt。(用cmd,用法:python 11.2countfile.py r2.txt)
我的代码:
import sys
import re
import os
def countfile(filename,words): #words 结果,为字典
try:
f = open(filename,'r',encoding='ANSI')
except Exception as e:
print(e)
return 0
txt = f.read()
f.close()
splitchars = set([])
for c in txt:
if not ('a' <= c <= 'z' or 'A' <= c <= 'Z'):
splitchars.add(c)
splitstr = ''
for c in splitchars:
if c in {'.','?','!','"',"'",'(',')','|','*','$','\\','[',']','^','{','}'}:
splitstr += '\\'+c+'|'
else:
splitstr += c+'|'
splitstr += ' '
lst = re.split(splitstr,txt)
for x in lst:
if x=='':
continue
lx = x.lower()
if lx in words:
words[lx] += 1
else:
words[lx] = 1
return 1
result = {}
lst = os.listdir()
for x in lst:
if os.path.isfile(x):
if x.lower().endwith('.txt') and x.lower().startswith('b1'): #以.txt结尾。startwith('..')以·..开始
countfile(x,result)
lst = list(result.items())
lst.sort()
f = open(sys.argv[1],'w')
for x in lst:
f.write('%s\t%d\n'%(x[0],x[1]))
f.close()
cmd结果出错:
程序位置:
由于我是初学者,以前从未接触过,请问是哪里出错了?要如何解决?谢谢大家解惑!
相似问题