How To Count One Specific Word In Python?
Solution 1:
You could just use str.count()
since you only care about occurrences of a single word:
withopen("log_file") as f:
contents = f.read()
count = contents.count("apple")
However, to avoid some corner cases, such as erroneously counting words like "applejack"
, I suggest that you use a regex:
import re
withopen("log_file") as f:
contents = f.read()
count = sum(1for match in re.finditer(r"\bapple\b", contents))
\b
in the regex ensures that the pattern begins and ends on a word boundary (as opposed to a substring within a longer string).
Solution 2:
If you only care about one word then you do not need to create a dictionary to keep track of every word count. You can just iterate over the file line-by-line and find the occurrences of the word you are interested in.
#!/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
However, if you also want to count all the words, and just print the word count for the word you are interested in then these minor changes to your code should work:
#!/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]
Solution 3:
You can use the Counter
dictionary for this
from collections import Counter
withopen("log_file", "r") as logfile:
word_counts = Counter(logfile.read().split())
print word_counts.get('apple')
Solution 4:
This is an example of counting words in array of words. I am assuming file reader will be pretty much similar.
def count(word, array):
n=0for x inarray:
if x== word:
n+=1return n
text='apple orange kiwi apple orange grape kiwi apple apple'
ar = text.split()
print(count('apple', ar))
Solution 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] + 1else:
d[i] = 1print(d)
Post a Comment for "How To Count One Specific Word In Python?"