首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >统计多个文件累计单词频率(python)?

统计多个文件累计单词频率(python)?

提问于 2023-08-04 16:55:18
回答 1关注 0查看 115

问题:在cmd中无法得出结果文件,出现错误,不知道如何改进。

题目要求:对当前文件夹(11.2countfiles.py 文件所在文件夹)下全部文件名是字母a打头的.txt文件 进行词频统计,统计的总的结果写入 "结果文件" r2.txt。(用cmd,用法:python 11.2countfile.py r2.txt)

我的代码:

代码语言:js
复制
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结果出错:

程序位置:

由于我是初学者,以前从未接触过,请问是哪里出错了?要如何解决?谢谢大家解惑!

回答

和开发者交流更多问题细节吧,去 写回答
相关文章

相似问题

相关问答用户
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档