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
172 views
in Technique[技术] by (71.8m points)

string - Count occurence of a word by ID in python

Following is the content of a file,My question is how to count the number of occurences for the word "optimus" for different IDs

    ID67    DATEUID Thank you for choosing Optimus prime. Please wait for an Optimus prime to respond. You are currently number 0 in the queue. You should be connected to an agent in approximately TIMEUID.. You are now chatting with AGENTUID   0
    ID67    Optimus MEMORYUID Hi there! Welcome to Optimus prime Web Chat. How can I help you today?        1       
    ID67    Optimus DATEUID I like to pay  prepaid from CURRENCYUID with NUMBERUID expiry on whateve date. my phone no is PHONEUID 2
    ID12120 0 0 0 is the number. They are open 0/0 so you can ring them anytime. SMILEUID   1
    ID12120 Thanks Optimus, I will give them a call. Thanks for your help! HELPUID  2
    ID5552  is the number. They are open 0/0 so you can ring them anytime. SMILEUID 1
    ID5552  Thanks Optimus, I will give them a call. Thanks for your help! HELPUID  2

for line in chat.txt:
   print line, ####print lines and count optimus word for the particular id..

Output should be like

ID67:4
ID12120
ID5552:1
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

One way is to use a defaultdict for the counts:

from collections import defaultdict
d = defaultdict(int)
with open("chat.txt") as f:
    for line in f:
        id, data = line.split(None, 1)
        d[id] += data.lower().count("optimus")

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

...