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
因此,我得到了单词列表:
['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'}
但是我需要一个dict,它的值看起来像是每个可能单词的列表,紧跟在关键字后面。例如,单词“fish”后跟4个单词,因此我需要:
'fish':['two', 'red', 'blue', 'one']
“蓝色”后跟“鱼”和“结束”
'blue':['one', 'end']
等等
拜托,有什么想法吗?你知道吗
该任务是生成随机句子的第一步。你知道吗
谢谢)
你可以试试这个:
它给出:
您不需要添加
start
和end
来避免访问超出列表大小的元素。你知道吗相关问题 更多 >
编程相关推荐