擅长:python、mysql、java
<pre class="lang-py prettyprint-override"><code>import collections, itertools
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = itertools.tee(iterable)
next(b, None)
return zip(a, b)
text = "I'm trying to count the number of occurrences of each letter combination in a text file"
counter = collections.Counter(pairwise(text))
</code></pre>
<p>“诀窍”是使用生成器(如我从python文档复制的生成器)来访问字母组合。它可以自然地扩展到三个或更多个字母。在</p>
<p>如果要忽略空白,请先将输入标记化。在</p>