gpt4 book ai didi

python - 如何从字典中造句

转载 作者:行者123 更新时间:2023-11-28 22:35:21 25 4
gpt4 key购买 nike

我正在尝试编写一些代码,让用户输入一个句子,将句子转换为字典,然后使用字典恢复原始句子。

代码:

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 boys”,你会发现没有索引为 1 的元素(boys, 4) 之后的字典将覆盖 (boys, 1)

关于python - 如何从字典中造句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38253719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com