Skip to main content
 首页 » 编程设计

Python:文件中的字母数,简单而有效的方法

2025年05月04日13Renyi-Fan

我想知道是否有更有效的方法来计算文件中的所有字母。我只需要来自 a..z 和 A..Z 的字母,所以像 '\n' 和 '\t' 这样的符号不算数。这是我的方式,但它比它应该花费更多的时间。

from string import ascii_lowercase 
in = open("file.txt", "r") 
f = in.read().lower() 
count = 0 
for i in f: 
    if i in ascii_lowercase: 
        count += 1 
print count 

我知道我可以使用大写字母,但它会改变什么吗。

请您参考如下方法:

I need just letters from a..z and A..Z (...) it takes more time than it should.

这应该很快。

import re 
infile='yourfile.txt' 
with open(infile) as f: 
    print len(re.sub('[^a-zA-Z]', '', f.read())) 

这种方法有几个很好的特性:

  • 易于使用其他模式进行扩展
  • 写作速度快
  • 节省时间和内存

然而,事实证明,这是一种非常有效的方法(在所有构建时间、运行时间和内存使用方面)建立在 PM2Ring 提出的想法之上,并使用所有的简单字符串应该计算的字符。它也很 pythonic:

# Beautiful is better than ugly. 
alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' 
with open(infile) as f: 
  return sum(1 for c in f.read() if c in alpha) 

注意:将上述解决方案与 findall, frozenset 的解决方案进行比较和 filter在具有 9.6KB 匹配 a..zA..Z 的 45KB 文件上给出以下计时结果。与效率问题一样,时间和空间 (YMMV) 之间存在权衡:

# findall 
1000 loops, best of 3: 1.62 ms per loop 
memory for temporary result: 77.8KB 
# frozenset 
100 loops, best of 3: 2.01 ms per loop 
memory for temporary result: 232B (frozenset) 
# string  
100 loops, best of 3: 3.02 ms per loop 
memory for temporary result: 89B (alpha string) 
# sub (my initial solution) 
100 loops, best of 3: 5.25 ms per loop 
memory for temporary result: 9.2KB 
# filter 
100 loops, best of 3: 7.7 ms per loop 
memory for temporary result: 9.2KB 

更新:

  • 删除了数字。如果您需要它们,请使用模式 [^a-zA-Z0-9]
  • 直接在sub中使用f.read(),性能提升约70%
  • 添加时间来比较几个提议的解决方案

如果文件太大,无法一次读取,分步处理:

CHUNK = 1024 * 1024 
letter_count = 0 
with open(infile) as f: 
    while True: 
        letter_count += len(re.sub('[^a-zA-Z]', '', f.read(CHUNK) if not None else '')) 
print letter_count