这是一个使用networkX解决问题的方案。
代码将生成一个有向图dG。每个单词将作为一个节点,其中“count”属性表示该单词出现的次数。每个相邻二元组将作为有向边连接起来,其中“weight”属性表示该二元组出现的次数。
import networkx as nx
import string
from sys import maxint
str1 = """Man who run in front of car, get tired.
Man who run behind car, get exhausted."""
wordList1 = str1.split(None)
wordList2 = [string.rstrip(x.lower(), ',.!?;') for x in wordList1]
dG = nx.DiGraph()
for i, word in enumerate(wordList2):
try:
next_word = wordList2[i + 1]
if not dG.has_node(word):
dG.add_node(word)
dG.node[word]['count'] = 1
else:
dG.node[word]['count'] += 1
if not dG.has_node(next_word):
dG.add_node(next_word)
dG.node[next_word]['count'] = 0
if not dG.has_edge(word, next_word):
dG.add_edge(word, next_word, weight=maxint - 1)
else:
dG.edge[word][next_word]['weight'] -= 1
except IndexError:
if not dG.has_node(word):
dG.add_node(word)
dG.node[word]['count'] = 1
else:
dG.node[word]['count'] += 1
except:
raise
要查看图表的内容,您可以打印节点和边。
for node in dG.nodes():
print '%s:%d\n' % (node, dG.node[node]['count'])
for edge in dG.edges():
print '%s:%d\n' % (edge, maxint - dG.edge[edge[0]][edge[1]]['weight'])
请注意,二元组边的权重不是从零开始计数,而是从maxint开始倒数计数。这是因为networkX的最短路径工具将使用权重值作为每条边的代价。通过将我们的最高计数变为最小的权重,我们可以使用这些工具找到具有最高边计数的路径。
例如,我们可以在单词“man”和单词“exhausted”之间获取具有最高计数的路径:
>>>shortest_path = nx.shortest_path(dG, source='man', target='exhausted', weight='weight')
>>>print shortest_path
['man', 'who', 'run', 'behind', 'car', 'get', 'exhausted']
或者,我们可以获取单词“man”和所有其他单词之间计数最高的路径:
>>>shortest_paths = nx.shortest_path(dG, source='man', weight='weight')
>>>print shortest_paths
{'run': ['man', 'who', 'run'],
'get': ['man', 'who', 'run', 'behind', 'car', 'get'],
'exhausted': ['man', 'who', 'run', 'behind', 'car', 'get', 'exhausted'],
'car': ['man', 'who', 'run', 'behind', 'car'],
'who': ['man', 'who'],
'behind': ['man', 'who', 'run', 'behind'],
'of': ['man', 'who', 'run', 'in', 'front', 'of'],
'in': ['man', 'who', 'run', 'in'],
'front': ['man', 'who', 'run', 'in', 'front'],
'tired': ['man', 'who', 'run', 'behind', 'car', 'get', 'tired'],
'man': ['man']}
如上所述,像这样的图可能存在循环,我不确定networkx最短路径算法在处理这种情况时是否能很好地处理。
祝好运!