Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何连接字典中文本的连续单词?_Python_List_Dictionary_Graph - Fatal编程技术网

Python 如何连接字典中文本的连续单词?

Python 如何连接字典中文本的连续单词?,python,list,dictionary,graph,Python,List,Dictionary,Graph,我必须在字典中连接文本中的连续单词 案文如下: text = "Hello world I am Josh" 字典将是: dict = {Hello:[world], world:[Hello, I], I:[am, world], am:[I, Josh], Josh:[am]} 键是文本中的所有单词,值是连续的单词。 有人想放弃这个吗 我会把文字分开。获取列表中的所有单词。 我会用这些词作为字典的索引。 ? 使用: 你的问题不考虑一个词出现在句子中不止一次的可能性。您可能需要一个集合,

我必须在字典中连接文本中的连续单词

案文如下:

text = "Hello world I am Josh"
字典将是:

dict = {Hello:[world], world:[Hello, I], I:[am, world], am:[I, Josh], Josh:[am]} 
键是文本中的所有单词,值是连续的单词。 有人想放弃这个吗

我会把文字分开。获取列表中的所有单词。 我会用这些词作为字典的索引。 ? 使用:

你的问题不考虑一个词出现在句子中不止一次的可能性。您可能需要一个集合,而不是相邻单词的列表。句子中的标点符号也可能毁掉你的一天,因此根据你的要求,你可能需要做的不仅仅是拆分。

使用:


你的问题不考虑一个词出现在句子中不止一次的可能性。您可能需要一个集合,而不是相邻单词的列表。句子中的标点符号也会毁了你的一天,因此根据你的要求,你可能需要做的不仅仅是拆分。

如果文本是西蒙和西蒙读的那本已经读过的书,你会期待什么?好问题,也许作为集合,dicts的值会更好。Counter比lists如果文本类似于Simon和Simon阅读了已经阅读过的书,你会期望什么?好问题,也许dicts的值作为集合会更好。Counter比listsDamn,我只是用不同的变量名写出了完全相同的代码,然后就要发布了。该死,我只是用不同的变量名写出了完全相同的代码,然后就要发布了。
def pairwise(iterable):
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

adjacent = collections.defaultdict(list)
for left, right in pairwise(text.split()):
    adjacent[right].append(left)
    adjacent[left].append(right)