Skip to content Skip to sidebar Skip to footer

Count Specific Word In File With

Im trying to count the number of occurrences of a word in a comma seperated file, using python. I have a file that contains strings like this: path/to/app1,app1,fail,my@email.com,l

Solution 1:

What you're doing is comparing lists (which are the result of a str.split) to the string fail, what you want to do is check if fail exists in these lines:

for line in lines:
   if "fail" in line.split(','):
       fails += 1

This code assumes fail can appear at most once, between commas.

The correct way to do this is using the csv module:

import csv
fails = 0withopen("logfile.log") as f:
    reader = csv.reader(f)
    for row in reader:
        for item in row:
            if item == "fail":
                fails += 1print fails

You can also use a collections.Counter to count:

import csv
from collections import Counter
counter = Counter()
withopen("logfile.log") as f:
    reader = csv.reader(f)
    for row in reader:
        counter.update(row)
print counter['fail']

Solution 2:

try this:

defspecific_word_count(text, specific_word):
    returnlen(text.split(specific_word)) - 1

input:

specific_word_count('abcdabcdabcd','a')

output:

3

Post a Comment for "Count Specific Word In File With"