我需要尝试将输入的字符串放入字典中的帮助
输入:
Hello my name is Bob Hello Hello
实际输出:
所需的输出:
{'Hello' : '1', 'my' : '2', 'name' : '3', 'is' : '4', 'Bob' : '5'}
只应记录一次相同的单词
到目前为止,我的代码:
s = input("input sentence: ")
file = open("Original.txt", 'w')
file.write(s)
file.write("\n")
file.close()
num = int(1,2,3,4,5)
dictionary = dict(num(s.split()))
file = open("Dictionary.txt", 'a')
file.write(dictionary)
file.close()
f = open("Dictionary.txt", 'r')
print(file.read)
print(s)
下面的代码将一个句子拆分成多个单词,然后按照您想要的方式将它们放在一个单独的单词中。
>>> string = 'Hello my name is bob'
>>> string = {v: k for k ,v in enumerate(string.split(), start=1)}
>>> string
{'bob': 5, 'is': 4, 'my': 2, 'Hello': 1, 'name': 3}
>>>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句