只給一個備選方案(我想其他的答案更適合您的需求),你可以使用來自itertools
的pairwise
配方:
from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
這時可把功能被編碼爲:
def word_counts(string):
words = string.split()
result = defaultdict(lambda: defaultdict(int))
for word1, word2 in pairwise(words):
result[word1][word2] += 1
return result
測試:
string = 'This is a string is not an int is a string'
print word_counts(string)
主要生產:
{'a': {'string': 2}, 'string': {'is': 1}, 'This': {'is': 1}, 'is': {'a': 2, 'not': 1}, 'an': {'int': 1}, 'int': {'is': 1}, 'not': {'an': 1}}
一個很好的解決辦法,但注意,從'zip'改爲'izip'顯著減少了字的大集合的運行時間(給出了1M的條目列表減少〜45%) – FujiApple
當然,是的情況下, python2。 – gukoff