python - 如何从字典中创建一个句子

标签 python string python-3.x dictionary input

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

代码:

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/

相关文章:

c++ - 如何正确地将标准输入中的值读入变量

python - Pandas - GroupBy 2 列 - 无法重置索引

python - 在 python 中声明文件夹路径的正确方法是什么?

Python 错误 : execute cannot be used while an asynchronous query is underway

c++ - 如何将 utf32 字符串转换为 Unicode 字符串

c - strtok 不只在指定的分隔符上标记

python-3.x - python 错误 "TypeError: ' int' 对象不可调用”

python - 如何使用/从命名空间中获取列表元素?

python - 如何将实例属性链接到 numpy 数组?

python - 如何从排列好的 numpy 数组中提取数组?