2012-10-29 28 views
-2

Possible Duplicate:
Reading a File into a Dictionary And Keeping Count從文件創建字典

我想創建帶有兩個值的字典:第一個值是文本:

<NEW ARTICLE> 
Take a look at 
what I found. 
<NEW ARTICLE> 
It looks like something 
dark and shiny. 
<NEW ARTICLE> 
But how can something be dark 
and shiny at the same time? 
<NEW ARTICLE> 
I have no idea. 

,第二個值是多少次的計數使用詞「ARTICLE>」。

我嘗試了不同的方法,一個方法我收到此錯誤:

我收到的erorr是這樣的:

(key, val) = line.split() 
ValueError: need more than 1 value to unpack 

我已經嘗試了幾種不同的方法,但都無濟於事,一個方法我試圖說,它提供了太多的值來解壓縮..

我希望能夠搜索字典中的關鍵字,並找到適當的計數。

使用Python 3

+0

你問了同樣的問題[h ERE](http://stackoverflow.com/questions/13115214/reading-a-file-into-a-dictionary-and-keeping-count)。通常不是一個好主意 – inspectorG4dget

回答

1

這應該這樣做:

>>> with open("data1.txt") as f: 
...  lines=f.read() 
...  spl=lines.split("<NEW ARTICLE>")[1:] 
...  dic=dict((i,x.strip()) for i,x in enumerate(spl)) 
...  print dic 
... 
{0: 'Take a look at \nwhat I found.', 
1: 'It looks like something\ndark and shiny.', 
2: 'But how can something be dark\nand shiny at the same time?', 
3: 'I have no idea.'} 
+0

嗯,當我打印時,我一直收到一個空字典,我正在使用Python 3. – Goose

+0

@Goose剛剛在python 3.x上測試了它,它工作正常。 –

+0

它可以工作,但是對於新手來說,這個概念有點棘手,可以解釋一下「dic = dict((i,x.strip())for i,x in enumerate(spl))」完全在你的答案?然後我可以選擇它是正確的。 – Goose

0

確保你沒有地方一個空行:

if newdoc == True and line != "ARTICLE>" and line: 
    (key, val) = line.split() 

(空行會分裂作爲[],它不能被解析爲具有兩個元素的元組......)

+1

還有一個問題:'line!=「ARTICLE>」'將始終爲真。 –

+0

但是如果'line ==「」',條件將不會被滿足。 –

+0

確實如此,但是他的所有代碼行都與「ARTICLE>」完全一樣,所以代碼肯定無法使用。也許不是line.endswith(「ARTICLE>」)...... –