我正在尝试编写一些代码,用户输入一个句子,该句子将转换为字典,然后使用该字典取回原始句子。
代码:
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
对于我重新创建原始句子的部分,它不能只打印句子,它必须来自字典。
最佳答案
您需要使用 OrderedDict
来保留元素顺序,或者在打印之前对字典元素进行排序。您已经获得了 OrderedDict
答案,因此以下是如何使用您创建的字典:
print(' '.join(k for (k, v) in sort(dictionary.items(), key=lambda x: x[1])))
顺便说一句,您的方法有一个错误:如果您将其应用于包含重复单词的句子,例如“boys will be boy”,您会发现在中没有索引为 1
的元素您的字典,因为 (boys, 4)
将覆盖 (boys, 1)
。
关于python - 如何从字典中创建一个句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38253719/