根据自己所学专业文字完成对一篇文章(文本文件)的词频统计,具体参照词频统计案例。
=====
https://blog.csdn.net/m0_61903191/article/details/123817563
不知道你这个问题是否已经解决, 如果还没有解决的话:问题解答:
# 导入需要使用的库
import os
import sys
import collections
# 定义读取文件函数
def read_file(file_path):
f = open(file_path, 'r', encoding='utf-8')
content = f.read()
f.close()
return content
# 定义词频统计函数
def word_count(content, word):
count = collections.Counter(content.split())
return count.get(word)
if __name__ == '__main__':
# 输入文件路径以及目标单词
file_path = input("请输入文件路径:")
word = input("请输入目标单词:")
# 判断文件是否存在
if not os.path.exists(file_path):
print("文件不存在")
sys.exit()
# 读取文件内容
content = read_file(file_path)
while True:
option = input("请选择需要执行的功能:1.进行词频统计,2.退出程序")
if option == "1":
# 进行词频统计
word_num = word_count(content, word)
print("单词'{}'出现的次数为:{}".format(word, word_num))
elif option == "2":
# 退出程序
print("退出程序")
sys.exit()
else:
# 输入错误,重新输入
print("输入错误,请重新输入")
解释:
这样就可以实现对指定文本的词频统计功能了。