2012-04-03 10 views
-1

は、ファイルの内容で、私の質問は、語「オプティマス」の出現箇所の数をカウントする方法である異なるIDのカウント出現

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 
+0

私たちはあなたが選択したアプローチ聞かせてください、なぜあなたが期待どおりに動作しませんでした。 – Fenikso

答えて

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

あなたは 'defaultdict'の代わりに' Counter'を使うべきで、組み込みの名前 'id'を変数として使うべきではありません。 – Kimvais

+0

@Kimvais:私は同意しない。 'Counter 'を使うこともできますが、この場合は何の利点もありません。 –

+0

私は利点があるかどうかについては同意しません - あなたが 'Counter'の場合にカウントするために使用することは自明であり、' defaultdict(int) 'の場合は__できません。 – Kimvais

1
>>> 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 
+0

私はループ内でSvenのコーディングがもっと好きです。 – KurzedMetal

関連する問題