使用正则表达式,我想要计算具体的字母。我做了一个匹配对象,如下所示。但不知道如何计算其频率。大多数计数的例子都是单词,所以我找不到好的参考。
f = open("C:\Python27\test.txt")
raw_sentence = f.read
upper_sentence = raw_sentence.upper()
match = re.findall(r"A", upper_sentence)
我应该像其他字数统计代码一样制作一些列表数据吗?
答案 0 :(得分:1)
只需使用str.count
:
raw_sentence.upper().count('A')
如果您想要多个元素的计数,最好使用collections.Counter
:
>>> s = 'abcabcsdab'
>>> import collections
>>> collections.Counter(s)
Counter({'a': 3, 'b': 3, 'c': 2, 'd': 1, 's': 1})