【问题标题】:Python: Creating a function counting specific words in a textfilePython:创建一个计算文本文件中特定单词的函数
【发布时间】:2020-02-17 09:12:07
【问题描述】:

我想创建一个函数,它返回文本文件中特定单词的字数值。

这是我目前拥有的:

def Word_Counter(Text_File, Word):

    Data = open(Text_File, 'r').read().lower()

    count = Data.count(Word)


    print(Word, "; ", count)

Word_Counter('Example.txt', "the")

返回:"the ; 35"

这几乎就是我想要它做的。但是,如果我想测试一个文本的一系列单词怎么办。我想要列表或字典中的单词(键)和值。不使用模块的方法是什么?

如果我用这个单词列表测试了这个函数:[时间、时间、离开、我、做、一个、谁、什么、有时]。

我想要的结果是这样的:

Word Counts = {'time': 1, 'when': 4, 'left': 0, 'I': 5, 'do': 2, 'an': 0, 'who': 1, 'what': 3, 'sometimes': 1}

我已经能够创建一个字典,对每个单词进行字数统计,如下例所示。

wordfreq = {}
for word in words.replace(',', ' ').split():
   wordfreq[word] = wordfreq.setdefault(word, 0) + 1

我想做一个类似的风格,但只针对特定的词,有什么建议吗?

【问题讨论】:

  • 顺便说一句,您可能应该阅读有关名称大写的 PEP-8。使用大写字母定义的函数和变量会使阅读更加混乱。

标签: python string list dictionary word-count


【解决方案1】:

根据您给定的代码,我没有对此进行测试。

def Word_Counter(Text_File, word_list):

        Data = open(Text_File, 'r').read().lower()
        output = {}
        for word in word_list:
           output[word] = Data.count(Word)

或者你可以这样做

text = open("sample.txt", "r") 

# Create an empty dictionary 
d = dict() 

# Loop through each line of the file 
for line in text: 
    # Remove the leading spaces and newline character 
    line = line.strip() 

    # Convert the characters in line to  
    # lowercase to avoid case mismatch 
    line = line.lower() 

    # Split the line into words 
    words = line.split(" ") 

    # Iterate over each word in line 
    for word in words: 
        # Check if the word is already in dictionary 
        if word in d: 
            # Increment count of word by 1 
            d[word] = d[word] + 1
        else: 
            # Add the word to dictionary with count 1 
            d[word] = 1

【讨论】:

  • 公平警告 - 大文件可能会中断。
  • 那太好了,你是对的。较大的文本文件可能会遇到困难。但是做我需要它做的事!谢谢!
【解决方案2】:

更新

尝试以下方法:

keywords = ['the', 'that']
worddict = {}

with open('out.txt', 'r') as f:
    text = f.read().split(' ')  # or f.read().split(',')

for word in text:
    worddict[word] = worddict[word]+1 if word in worddict else 1

print([{x, worddict[x]} for x in keywords])

【讨论】:

  • 这似乎返回文本中每个单词的字数,而不是关键字?
  • @AllenPeck 这根本不是问题 :) 查看更新
猜你喜欢
  • 1970-01-01
  • 2011-05-30
  • 1970-01-01
  • 1970-01-01
  • 2014-11-04
  • 2012-10-31
  • 1970-01-01
  • 1970-01-01
  • 2016-09-09
相关资源
最近更新 更多