5

我是一名初学者 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

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

4

8 回答 8

12

This is very readable way to accomplish what you want using 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)

You can iterate the resulting dict to print it in the format that you want.

于 2013-09-05T23:55:13.940 回答
1

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

It is much more elegant and clean with Counter nonetheless.

于 2013-09-06T00:29:43.337 回答
1

You have to use collections.Counter

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

It prints:

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

Your text variable should be:

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 getting the output you need:

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

In my example it prints:

a 5
c 5
b 5

For more information Counters doc

于 2013-09-05T23:52:32.243 回答
1
import string
fp=open('text.txt','r')
file_list=fp.readlines()
print file_list
freqs = {}
for line in file_list:
    line = filter(lambda x: x in string.letters, line.lower())
    for char in line:
        if char in freqs:
            freqs[char] += 1
        else:
            freqs[char] = 1

print freqs
于 2013-09-06T05:53:18.030 回答
1

只是为了完整起见,如果你想在不使用的情况下这样做Counter,这是另一种非常简短的方法,使用列表理解和dict内置:

from string import ascii_lowercase as letters
with open("text.txt") as f:
    text = f.read().lower()
    print dict((l, text.count(l)) for l in letters)

f.read()将整个文件的内容读入text变量(如果文件真的很大,可能是个坏主意);然后我们使用列表推导来创建一个元组(letter, count in text)列表并将这个元组列表转换为字典。使用 Python 2.7+,您还可以使用{l: text.count(l) for l in letters}更短且更具可读性的 .

但是请注意,这将多次搜索文本,每个字母一次,而Counter只扫描一次并一次更新所有字母的计数。

于 2013-09-06T08:40:51.010 回答
0

您可以将问题拆分为两个更简单的任务:

#!/usr/bin/env python
import fileinput # accept input from stdin and/or files specified at command-line
from collections import Counter
from itertools import chain
from string import ascii_lowercase

# 1. count frequencies of all characters (bytes on Python 2)
freq = Counter(chain.from_iterable(fileinput.input())) # read one line at a time

# 2. print frequencies of ascii letters
for c in ascii_lowercase:
     n = freq[c] + freq[c.upper()] # merge lower- and upper-case occurrences
     if n != 0:
        print(c, n)
于 2013-09-06T11:41:37.057 回答
0

还有一种方式:

import sys
from collections import defaultdict

read_chunk_size = 65536

freq = defaultdict(int)
for c in sys.stdin.read(read_chunk_size):
    freq[ord(c.lower())] += 1

for symbol, count in sorted(freq.items(), key=lambda kv: kv[1], reverse=True):
    print(chr(symbol), count)

它输出最频繁到最少的符号。

字符计数循环是 O(1) 复杂度,并且可以处理任意大的文件,因为它以read_chunk_size块的形式读取文件。

于 2019-04-27T18:35:36.763 回答
-1
import sys

def main():
    try:
         fileCountAllLetters = file(sys.argv[1], 'r')
         print "Count all your letters: ", len(fileCountAllLetters.read())
    except IndexError:
         print "You forget add file in argument!"
    except IOError:
         print "File like this not your folder!"

main()

python file.py countlettersfile.txt

于 2019-04-27T18:15:39.367 回答