本文介绍了通过ID在python中计数一个字的发生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是文件的内容,我的问题是如何计算不同ID的单词optimus的出现次数

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

输出应该像

ID67:4
ID12120
ID5552: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")

这篇关于通过ID在python中计数一个字的发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 17:16