【问题标题】:Count occurence of a word by ID in python在python中按ID计算单词的出现次数
【发布时间】:2012-04-03 13:23:10
【问题描述】:

下面是一个文件的内容,我的问题是如何统计不同ID下“optimus”这个词的出现次数

    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..

输出应该是这样的

ID67:4
ID12120
ID5552:1

【问题讨论】:

  • 请告诉我们您选择了哪种方法以及为什么它没有按您的预期工作。

标签: python string count


【解决方案1】:

一种方法是使用defaultdict 进行计数:

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

【讨论】:

  • 您应该使用Counter 而不是defaultdict,也不应该使用内置名称id 作为变量。
  • @Kimvais:我不同意。您也可以使用Counter,但在这种特殊情况下没有任何优势。
  • 我不同意这是否有优势 - 任何人 很明显,如果它是 Counter,您将使用它来计数,而 不是 defaultdict(int) 的情况。
  • 我更喜欢 Kimvais 对 Counter 的使用。
  • 但计数器仅在 python 2.6.5 之后可用,所以可能是 Sven Marnach 是对的.....
【解决方案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})

您可以将值打印为:

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

【讨论】:

  • 我更喜欢 Sven 在循环中的编码。
猜你喜欢
  • 1970-01-01
  • 2012-08-09
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多