2016-06-17 60 views
-2

我需要幫助試圖把輸入的字符串轉換成字典Python的 - 將一個字符串轉換成字典

輸入:

Hello my name is Bob Hello Hello 

實際輸出:

所需的輸出:

{'Hello' : '1', 'my' : '2', 'name' : '3', 'is' : '4', 'Bob' : '5'} 

應該只記錄同一個詞一度

我迄今爲止代碼:

s = input("input sentence: ") 
    file = open("Original.txt", 'w') 
    file.write(s) 
    file.write("\n") 
    file.close() 
    num = int(1,2,3,4,5) 
    dictionary = dict(num(s.split())) 
    file = open("Dictionary.txt", 'a') 
    file.write(dictionary) 
    file.close() 
    f = open("Dictionary.txt", 'r') 
    print(file.read) 
    print(s) 
+1

試試這個:http://stackoverflow.com/questions/988228/converting-a-string-to-dictionary – Nikita

+1

1.什麼是你到目前爲止的代碼做什麼,以及如何從您的期望有所不同; 2.有什麼可笑的評論? – jonrsharpe

+0

我需要它,因此字典中的數字沒有輸入 –

回答

0

下面的代碼拆分句子轉化成單詞並將其放入一個dcitionary在你想要的方式。

>>> string = 'Hello my name is bob' 
>>> string = {v: k for k ,v in enumerate(string.split(), start=1)} 
>>> string 
{'bob': 5, 'is': 4, 'my': 2, 'Hello': 1, 'name': 3} 
>>> 
+0

號如果輸入的是'你好,我的名字是鮑勃你好Hello',這將返回' {'Bob':5,'Hello':7,'is':4,'my':2,'name':3}'。因爲它會更新'「Hello」:1',首先使用'「Hello」:6',然後使用'「Hello」:7'。 –

+0

@emre。即基於OP的未定義行爲,如果應該保留該詞的第一次出現,則從未指定該行爲。 –

+0

@Tadhg McDonald-Jensen OP表示希望的輸出是'{'Hello':1,'my':2,'name':3,'is':4,'Bob':5} 'Hello':7,'my':2,'name':3,'is':4,'Bob':5}'這不是所需的輸出。 –