2016-07-07 56 views
2

我想在用戶輸入句子的地方製作一些代碼,將句子轉換爲字典,然後使用字典獲取原始句子。如何從字典中創建一個句子

代碼:

import json 
def code(): 
    sentence = input("Please write a sentence: ") 
    dictionary = {v: k for k,v in enumerate(sentence.split(), start=1)} 
    with open('Dict.txt', 'w') as fp: 
     json.dump(dictionary, fp) 
    print(dictionary) 
    puncList = ["{","}",",",":","'","[","]","1","2","3","4","5"] 
    for i in puncList: 
     for sentence in dictionary: 
      dictionary=[sentence.replace(i," ") for sentence in dictionary] 
    print(' '.join(dictionary)) 
code() 

輸入:

Hello my name is Bob 

實際輸出:

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

希望的輸出:

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

這將是罰款太:

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

對於那些我重新原判的一部分,它不能只是打印了一句,它必須是從字典。

+0

您可以使用OrderedDict –

回答

2

您需要使用OrderedDict來保留元素順序,或者在打印出字典元素之前排序字典元素。你已經有了一個OrderedDict答案,所以這裏是如何使用您創建的字典:

print(' '.join(k for (k, v) in sort(dictionary.items(), key=lambda x: x[1]))) 

順便說一句,你的方法有一個缺陷:如果你將它應用到一個句子重複的單詞,如「男生會是男孩「,你會發現在你的字典裏沒有索引1的元素,因爲(boys, 4)會覆蓋(boys, 1)

1

使用OrderedDictenumerate,就像這樣:

from collections import OrderedDict 

s = "Hello my name is Bob" 

d = OrderedDict((v, i) for i, v in enumerate(s.split(), 1)) 
print(d) 
# OrderedDict([('Hello', 1), ('my', 2), ('name', 3), ('is', 4), ('Bob', 5)]) 

s_rebuild = ' '.join(d) 
print(s_rebuild) 
# 'Hello my name is Bob' 

由於字典已經下令,值不用於重建的字符串。

1

您邏輯缺陷在於不能重複的單詞的句子處理:

Hello Bob my name is Bob too 
{'name': 4, 'Hello': 1, 'Bob': 6, 'is': 5, 'too': 7, 'my': 3} 
name Hello Bob is too my 

我們可以處理,使用一個defaultdict,使得字位置,而不是單個數字的值數組。我們可以通過處理您的打孔清單通過拆分。最後,我們可以使用一對嵌套循環重建原始語句。我們不希望/需要一個OrderedDict或排序,要做到這一點:

import re 
import json 
from collections import defaultdict 

PUNCH_LIST = r"[ {},:'[\]1-5]+" 

def code(): 
    dictionary = defaultdict(list) 

    sentence = input("Please write a sentence: ") 

    for position, word in enumerate(re.split(PUNCH_LIST, sentence), start=1): 
     dictionary[word].append(position) 

    with open('Dict.txt', 'w') as fp: 
     json.dump(dictionary, fp) 

    print(dictionary) 

    position = 1 
    sentence = [] 

    while position: 
     for word, positions in dictionary.items(): 
      if position in positions: 
       sentence.append(word) 
       position += 1 
       break 
     else: 
      position = 0 

    print(' '.join(sentence)) 

code() 

例:

Please write a sentence: Hello Bob, my name is Bob too 
defaultdict(<class 'list'>, {'is': [5], 'too': [7], 'Bob': [2, 6], 'Hello': [1], 'name': [4], 'my': [3]}) 
Hello Bob my name is Bob too 

其中Dict.txt包含:

{"is": [5], "too": [7], "Bob": [2, 6], "Hello": [1], "name": [4], "my": [3]} 

注意defaultdict是一種方便,而不是要求。一個普通的字典會做,但你必須初始化每個鍵的列表。