在文本fi中计数字母

2024-09-27 07:26:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个初级的python程序员,我正在尝试做一个程序,计算文本文件中的字母数。到目前为止我得到的是:

import string 
text = open('text.txt')
letters = string.ascii_lowercase
for i in text:
  text_lower = i.lower()
  text_nospace = text_lower.replace(" ", "")
  text_nopunctuation = text_nospace.strip(string.punctuation)
  for a in letters:
    if a in text_nopunctuation:
      num = text_nopunctuation.count(a)
      print(a, num)

如果文本文件包含hello bob,我希望输出为:

b 2
e 1
h 1
l 2
o 2

我的问题是,当文本文件包含多行文本或有标点符号时,它不能正常工作。


Tags: textinimport程序forstring字母open
3条回答

使用re:

import re

context, m = 'some file to search or text', {}
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
for i in range(len(letters)):
  m[letters[i]] = len(re.findall('{0}'.format(letters[i]), context))
  print '{0} -> {1}'.format(letters[i], m[letters[i]])

它是更优雅和干净的柜台,尽管如此。

这是使用Counter完成所需任务的非常可读的方法:

from string import ascii_lowercase
from collections import Counter

with open('text.txt') as f:
    print Counter(letter for line in f 
                  for letter in line.lower() 
                  if letter in ascii_lowercase)

您可以迭代得到的dict,以您想要的格式打印它。

你必须使用collections.Counter

from collections import Counter
text = 'aaaaabbbbbccccc'
c = Counter(text)
print c

它打印:

Counter({'a': 5, 'c': 5, 'b': 5})

您的text变量应该是:

import string
text = open('text.txt').read()
# Filter all characters that are not letters.
text = filter(lambda x: x in string.letters, text.lower())

为了获得所需的输出:

for letter, repetitions in c.iteritems():
    print letter, repetitions

在我的示例中,它打印:

a 5
c 5
b 5

有关详细信息Counters doc

相关问题 更多 >

    热门问题