2014-12-03 134 views
-2

我有我想開,變成一本字典,像這樣的文本文件:如何將文本轉換成字典在Python

文本在文本文件中:

「在過去十年來,對爬行類哺乳動物的興趣下降幾乎沒有引人注意。「

轉換爲詞典:

{'during' : 'the', 'the' : 'last', 'last' : 'ten', 'ten' : 'years', 'years' : 'the' ...etc } 

以便在文本文件中的每個詞被接通與以下單詞是其值的鍵。

我到目前爲止的代碼是這樣的:

def makedict(): 
    with open('textfile.txt') as f: 
     d = dict(line.strip().split(None, 1) for line in f) 
     return d 
print(makedict()) 

但是當我運行它,它打印出的第一個字爲重點,其餘爲值,就像這樣:

{在過去的十年中,對爬行類哺乳動物的興趣下降幾乎沒有引起注意。 }

+4

你'makedict'函數不返回它創建的'd'結果與返回'None'實際上是一樣的。 – bgporter 2014-12-03 14:38:49

+0

我現在試過了,它仍然沒有做到我想要的 – Sara 2014-12-03 14:42:57

+0

這是怎麼用重複鍵?您最終會擁有多個值相同的密鑰。 – Ffisegydd 2014-12-03 14:45:21

回答

0
def makedict(): 
    with open('textfile.txt') as f: 
     words = [i.strip().lower() for i in f.read().split()] 
     return dict(zip(words[:-1], words[1:])) 

>>> makedict() 
{'mammals': 'has', 'last': 'ten', 'been': 'barely', 'ten': 'years,', 'during': 'the', 'decrease': 'in', 'interest': 'in', 'reptilian': 'mammals', 'barely': 'noticeable.', 'has': 'been', 'the': 'decrease', 'years,': 'the', 'in': 'reptilian'} 

注意:字典只能有唯一的鍵。這意味着如果您有重複的單詞,則只有最近的值會出現在結果字典中,因爲之前的所有值都會被覆蓋。

例如注意到字典只有

{'the': 'decrease'} 

而不是

{'the': 'last', 'the': 'decrease'} 

因爲你不能有重複鍵

我不知道你打算如何使用這本字典,但請記住這一點。

+2

我想他想要的鑰匙是以前的價值,所以他希望每個單詞都是鑰匙 – user2097159 2014-12-03 14:44:02

+0

@ user2097159 100%正確 – heinst 2014-12-03 14:46:53

+0

這正是這樣做的。然而,我注意到有關重複鍵的警告。 – CoryKramer 2014-12-03 14:47:25

0
dic={} 

p="During the last ten years, the decrease in interest in reptilian mammals has been barely noticeable" 


x=zip(p.split(),p.split()[1:]) 
for k,y in x: 
    dic[k]=y 
print dic 
0

如果有重複鍵,你應該值追加到一個列表,你還需要使用一些剝去逗號等:

from collections import defaultdict 
spl = p.split() 
d = defaultdict(list) 
for a,b in zip(spl, spl[1:]): 
    d[a.translate(None,".,")].append(b.translate(None,".,")) 
print(d) 

defaultdict(<type 'list'>, {'last': ['ten'], 'ten': ['years'], 'reptilian': ['mammals'], 'barely': ['noticeable'], 'mammals': ['has'], 'years': ['the'], 'decrease': ['in'], 'been': ['barely'], 'interest': ['in'], 'in': ['interest', 'reptilian'], 'During': ['the'], 'the': ['last', 'decrease'], 'has': ['been']})