Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

python - 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,[email protected],logfile.log
path/to/app2,app2,success,[email protected],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

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

1 Reply

0 votes
by (71.8m points)

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']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...