python - 如何使用python查找文本文件中单词的频率?但是用户应该给出输入词
问题描述
我的目标:计算用户在文本文件中输入单词的频率。(在python中)我试过这个。但是它给出了文件中所有单词的频率。我怎样才能修改它来给出一个单词的频率由用户输入?
from collections import Counter
word=input("Enter a word:")
def word_count(test6):
with open('test6.txt') as f:
return Counter(f.read().split())
print("Number of input words in the file :",word_count(word))
这可能是一个幼稚的问题,但我才刚刚开始编码。所以请尝试回答。提前致谢。
解决方案
要查找文件中单词的频率,您可以使用连接文件中的所有行str.join
,然后使用str.count
:
def word_count(word):
with open('test6.txt') as f:
return ''.join(f).count(word)
print("Number of words in the file :", word_count(input('give me a word')))
您也可以在文本中使用字数统计:
def word_count(word):
with open('test6.txt') as f:
return f.read().count(word)
推荐阅读
- vb.net - 如何以字节为单位读取注册表值
- java - Java 应用程序无法在控制台窗口中显示结果
- java - 如何为我刚刚创建的新线程获取 Looper?
- google-apps-script - 从 Apps 脚本获取完整的 Google 相册网页
- linux - How to add a number at the end of a certain line for multiple files in Linux?
- python-3.x - 检查一列值是否在熊猫的另一列中
- angular - 具有延迟加载的 Ionic 4 和 Angular 8 CanActivate Route
- java - 具有因变量和对数增量的嵌套循环的时间复杂度
- julia - 如何确定字典是否有某个键?
- javascript - React 组件未在 history.push 上重新加载