2013-07-04 40 views
-1

我有一個製表符分隔的文件,我試圖從中提取特定的信息。本質上,我想搜索每一行,找到一個標識符,然後計算出現在文本中的次數。我通過文字要循環和存儲在字典中的信息..在python中識別和計算文本

這是我到目前爲止有:

c_count = {"c1":0, "c2":0, "c3":0, "c4":0, "c5":0} 

analysis = open("myInputFileName") 

for x in c_count: 
    if line in analysis == x 
     c_count[x] = c_count[x] + 1 

     print c_count 

我得到的錯誤:

if line in analysis == x 
         ^
SyntaxError: invalid syntax 

我在做什麼錯誤..? 謝謝!

回答

0

你錯過了:

if line in analysis == x: 
         ^
         | 

嘗試是這樣的:

c_count = {"c1":0, "c2":0, "c3":0, "c4":0, "c5":0} 
with open("myInputFileName") as analysis: 
    for line in analysis:   #read lines one by one 
     line = line.strip()   #strip white-spaces 
     if line in c_count:   #if line is found in c_count, increase it's count 
      c_count[line] += 1 
+0

這將是在任何情況下,錯誤的測試。 –

+0

ahhh非常感謝你。這個例子非常有幫助。對於新手的錯誤感到遺憾 - 我只是剛剛開始學習python。 – user2545406

+0

@ user2545406很高興幫助。 :)如果它適合你,請隨時[接受答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235)。 –