【问题标题】:How to count one specific word in Python?如何在 Python 中计算一个特定的单词?
【发布时间】:2016-07-15 16:34:27
【问题描述】:

我想统计文件中的特定单词。

例如“apple”在文件中出现了多少次。 我试过这个:

#!/usr/bin/env python
import re 

logfile = open("log_file", "r") 

wordcount={}
for word in logfile.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1
for k,v in wordcount.items():
    print k, v

通过将“word”替换为“apple”,但它仍会计算我文件中所有可能的单词。

任何建议将不胜感激。 :)

【问题讨论】:

标签: python


【解决方案1】:

您可以只使用str.count(),因为您只关心单个单词的出现:

with open("log_file") as f:
    contents = f.read()
    count = contents.count("apple")

但是,为了避免一些极端情况,例如错误地计算 "applejack" 这样的单词,我建议您使用 regex

import re

with open("log_file") as f:
    contents = f.read()
    count = sum(1 for match in re.finditer(r"\bapple\b", contents))
正则表达式中的

\b 确保模式在 单词边界 开始和结束(而不是较长字符串中的子字符串)。

【讨论】:

    【解决方案2】:

    如果您只关心一个单词,那么您不需要创建字典来跟踪每个单词的数量。您可以逐行遍历文件并找到您感兴趣的单词的出现。

    #!/usr/bin/env python
    
    logfile = open("log_file", "r") 
    
    wordcount=0
    my_word="apple"
    for line in logfile:
        if my_word in line.split():
            wordcount += 1
    
    print my_word, wordcount
    

    但是,如果您还想计算所有单词,并且只打印您感兴趣的单词的字数,那么对您的代码进行这些小的更改应该可以工作:

    #!/usr/bin/env python
    import re 
    
    logfile = open("log_file", "r") 
    
    wordcount={}
    for word in logfile.read().split():
        if word not in wordcount:
            wordcount[word] = 1
        else:
            wordcount[word] += 1
    # print only the count for my_word instead of iterating over entire dictionary
    my_word="apple"
    print my_word, wordcount[my_word]
    

    【讨论】:

    • 这会在"Hello, apple!"这样的句子中错过"apple"
    • 是的,但问题没有提到是否需要处理这些极端情况。 OP 表示,与其像她的代码那样计算每个单词,解决方案应该只计算一个单词,因此我的回答只是这样做。然而,一个正则表达式(而不是简单的 if)来指定一个人想要做的匹配类型将在不改变代码的其他部分的情况下工作。
    【解决方案3】:

    您可以为此使用Counter 字典

    from collections import Counter
    
    with open("log_file", "r") as logfile:
        word_counts = Counter(logfile.read().split())
    
    print word_counts.get('apple')
    

    【讨论】:

      【解决方案4】:

      这是一个在单词数组中计算单词的示例。我假设文件阅读器会非常相似。

      def count(word, array):
          n=0
          for x in array:
              if x== word:
                  n+=1
          return n
      
      text= 'apple orange kiwi apple orange grape kiwi apple apple'
      ar = text.split()
      
      print(count('apple', ar))
      

      【讨论】:

        【解决方案5】:
        def Freq(x,y):
            d={}
            open_file = open(x,"r")
            lines = open_file.readlines()
            for line in lines:
                word = line.lower()
                words = word.split()
                for i in words:
                    if i in d:
                        d[i] = d[i] + 1
                    else:
                        d[i] = 1
            print(d)
        

        【讨论】:

        • 虽然这个答案可能是正确且有用的,但最好在其中附上一些解释来解释它如何帮助解决问题。如果有更改(可能不相关)导致它停止工作并且用户需要了解它曾经是如何工作的,这在未来变得特别有用。
        【解决方案6】:
        fi=open("text.txt","r")
        cash=0
        visa=0
        amex=0
        for line in fi:
            k=line.split()
            print(k)
            if 'Cash' in k:
                cash=cash+1
            elif 'Visa' in k:
                visa=visa+1
            elif 'Amex' in k:
                amex=amex+1
        
        print("# persons paid by cash are:",cash)
        print("# persons paid by Visa card are :",visa)
        print("#persons paid by Amex card are :",amex)
        fi.close()
        

        【讨论】:

        • 欢迎来到 Stack Overflow!请添加一些解释以阐明您认为您的代码解决问题的原因。
        猜你喜欢
        • 2021-12-12
        • 2020-10-04
        • 1970-01-01
        • 1970-01-01
        • 2020-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多