sentence="one fish two fish red fish blue fish one
red two blue"
sentence='start '+sentence+' end'
word_list=sentence.split(' ')
d={}
for i in range(len(word_list)-1):
d[word_list[i]]=word_list[i+1]
print word_list
print d
因此,我得到了word_list:
['start', 'one', 'fish', 'two', 'fish', 'red',\
'fish', 'blue', 'fish', 'one', 'red', 'two',\
'blue', 'end']
和d:
{'blue': 'end', 'fish': 'one', 'two': 'blue',\
'one': 'red', 'start': 'one', 'red': 'two'}
但是我需要一个字典,其值看起来像是关键字后面的每个可能单词的列表。例如,单词“fish”后面跟着 4 个单词,所以我需要:
'fish':['two', 'red', 'blue', 'one']
“blue”后跟“fish”和“end”
'blue':['one', 'end']
等等
请问,有什么想法吗?
该任务是生成随机句子的第一步。
谢谢))
最佳答案
你可以尝试这个:
from collections import defaultdict
sentence="one fish two fish red fish blue fish one red two blue"
word_list = sentence.split()
d = defaultdict(list)
for a, b in zip( word_list, word_list[1:]) :
d[a].append(b)
print d
它给出:
{
"blue": [ "fish" ],
"fish": [ "two", "red", "blue", "one" ],
"two": [ "fish", "blue" ],
"red": [ "fish", "two" ],
"one": [ "fish", "red" ]
}
并且您不需要添加 start
和 end
来避免访问超出列表大小的元素。
关于python - 像列表一样生成字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51798405/