我正在尝试制作一些代码,其中用户输入一个句子,句子变成一个字典,然后dict用于获取原始句子。
代码:
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 :(得分:2)
您需要使用OrderedDict
来保留元素顺序,或者在打印之前对字典元素进行排序。您已经有OrderedDict
个答案了,所以这里是如何使用您创建的字典:
print(' '.join(k for (k, v) in sort(dictionary.items(), key=lambda x: x[1])))
顺便说一句,你的方法有一个错误:如果你把它应用到一个带有重复单词的句子,例如,"男孩将是男孩",你会发现没有元素由于1
将覆盖(boys, 4)
,因此您的字典中包含索引(boys, 1)
。
答案 1 :(得分:1)
在OrderedDict
上使用enumerate
,如下所示:
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'
由于字典已经排序,因此这些值不会用于重建字符串。
答案 2 :(得分: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是一种便利,而不是一项要求。普通字典可以,但您必须初始化每个键的列表。