计算字母组合的出现次数

时间:2016-01-19 23:32:05

标签: python string python-3.x

我正在尝试计算文本文件中每个字母组合的出现次数:

'aa','ab',...'zy','zz'

我已经设法能够使用collections.Counter轻松地计算单个字母的出现次数,我只是想知道2个字母组合是否有类似的方法。

由于

3 个答案:

答案 0 :(得分:1)

如果您只是想要这些字母,您可以过滤非字母,您不需要在内存中存储任何额外的数据,您所要做的就是链接字符并每次跟踪前一个字符:

from collections import Counter
from itertools import chain

with open("in.txt") as f:
    prev = f.read(1)
    c = Counter()
    for ch in filter(str.isalpha, chain.from_iterable(f)):
        c[prev + ch] += 1
        prev = ch
print(c)

如果您想要所有字符只删除过滤器:

with open("in.txt") as f:
    prev = f.read(1)
    c = Counter()
    for ch in chain.from_iterable(f):
        c[prev + ch] += 1
        prev = ch
print(c)

答案 1 :(得分:0)

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))

“技巧”是使用生成器,就像我从python文档中复制的那样,来访问字母组合。它可以自然地扩展到三个或更多字母。

如果要忽略空格,请先对输入进行标记。

答案 2 :(得分:0)

from collections import Counter

txt = "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"

txt1 = txt[:-1]
txt2 = txt[1:]
print (Counter([t1+t2 for t1, t2 in zip(txt1,txt2)]))