2016-07-15 69 views
3

我想计算文件中的特定单词。如何计算Python中的一个特定单词?

例如'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 

与“苹果”取代“字”,但也应算做我的文件中的所有可能的单词。

任何意见将不胜感激。 :)

+0

这些退房查看:蟒蛇 - 找到这个词的一个文件中出现(http://stackoverflow.com/问题/ 15083119/python-find-the-the-word-in-a-file),[用文件计算特定单词](http://stackoverflow.com/questions/29213458/count-specific- word-in-file-with) – davedwards

回答

7

你可以只使用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确保图案的开始和一个字边界上(结束,而不是一个子瓦特ithin更长的字符串)。

6

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

#!/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] 
+1

这会在''Hello,apple!“'这样的句子中错过''apple'''。 –

+0

是的,但这个问题并没有提及像这些角落案件需要处理。 OP表示,不是像她的代码那样计算每个单词,解决方案应该只计算一个单词,因此我的答案只能这样做。然而,用于指定匹配类型的正则表达式(而不是简单的if)可以在不改变其他代码部分的情况下工作。 – Wajahat

0

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

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)) 
1

可以使用Counter字典这个

from collections import Counter 

with open("log_file", "r") as logfile: 
    word_counts = Counter(logfile.read().split()) 

print word_counts.get('apple') 
-2
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() 
+0

欢迎来到Stack Overflow!请添加一些解释来阐明您认为您的代码解决问题的原因。 – ekhumoro

相关问题