首页 > 解决方案 > 如何使用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))

这可能是一个幼稚的问题,但我才刚刚开始编码。所以请尝试回答。提前致谢。

标签: pythonpython-3.x

解决方案


要查找文件中单词的频率,您可以使用连接文件中的所有行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)

推荐阅读