Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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,logfile.log
path/to/app2,app2,success,my@email.com,logfile.log

I want to find the out how many times "fail" is in the file.

I tried several things including

for line in lines:
   if line.split(',') == "fail":
       fails += 1
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
222 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 = 0
with open("logfile.log") as f:
    reader = csv.reader(f)
    for row in reader:
        for item in row:
            if item == "fail":
                fails += 1
print fails

You can also use a collections.Counter to count:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...