bin1010258497 发表于 2023-5-31 09:07 
因为你return位置不对,return不应该在第一个循环底下,应该循环结束之后再retune
谢谢!!!刚刚计算出来了,我还有一个问题,就是我现在已经计算出来关键词的词频了,怎么才能计算出来一个txt文件所有的词的总数?然后导出到excel。我在网上找到了代码,但是他是计算一个文档的,我修改之后一直跑不出来。能帮我看看么??
- def count_words(ThePath):
- ''' 方法:统计file_name中总词数 '''
- files=os.listdir(ThePath)
- for file in files:
- try:
- with open(file,encoding='utf-8') as file_object:
- message = file_object.read()
- except FileNotFoundError:
- print("The file '" + file + "' is NOT exist!")
- with open('missing_files.txt','a') as error_record:
- error_record.write(file+"\n")
- ''' 文件不存在时向用户输出提示,并记录错误信息到missing_files.txt中 '''
- else:
- words = message.split()
- length = len(words)
- print(file+ " has " + str(length) + " words in total.")
- file_object.save(aim_path)
- ThePath=r'E:\python相关\年报爬取\年报txt'
- aim_path=r'E:\python相关\年报爬取\词频统计'
复制代码