Count occurence of a word by ID in python

一笑奈何 提交于 2020-01-07 08:32:07

问题


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

回答1:


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")



回答2:


>>> from collections import Counter
>>> c = Counter()
>>> for line in chat.txt:
...     c[line.strip().split(" ",1)[0]] += line.count("Optimus")
>>> c
Counter({'ID67': 5, 'ID5552': 1, 'ID12120': 1, '': 0})

and you can print out the values as:

>>> for k, v in c.items():
...     print("{}:{}".format(k, v))
... 
:0
ID67:5
ID5552:1
ID12120:1


来源:https://stackoverflow.com/questions/9994195/count-occurence-of-a-word-by-id-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!