Skip to main content
 首页 » 编程设计

Python:计算文件行中一组特定字符的出现次数

2025年05月04日14虾米哥

我正在努力编写一个 Python 小程序,该程序旨在计算文本文件行中特定字符集的出现次数。

举个例子,如果我想计算 '!'和以下几行中的“@”

hi! 
hello@gmail.com 
collection! 

我希望得到以下输出:

!;2 
@;1 

到目前为止,我得到了一个功能代码,但它效率低下并且没有发挥 Python 库的潜力。 我试过使用 collections.counter,但收效有限。我发现的效率障碍是我无法在 counter.update() 上选择特定的字符集,找到的所有其余字符也被计算在内。然后我将不得不过滤我不感兴趣的字符,这增加了另一个循环...... 我也考虑过正则表达式,但我看不出在这种情况下有什么优势。

这是我现在拥有的功能代码(我能想到的最简单的想法),它在文件行中查找特殊字符。我想看看是否有人可以想出一个更简洁的特定于 Python 的想法:

 def count_special_chars(filename): 
      special_chars = list('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ ') 
      dict_count = dict(zip(special_chars, [0] * len(special_chars))) 
 
      with open(filename) as f: 
          for passw in f: 
              for c in passw: 
                  if c in special_chars: 
                      dict_count[c] += 1 
      return dict_count 

感谢检查

请您参考如下方法:

为什么不统计整个文件呢?您应该避免为文件的每一行循环遍历字符串。请改用 string.count。

from pprint import pprint 
 
# Better coding style: put constant out of the function 
SPECIAL_CHARS = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ ' 
 
def count_special_chars(filename): 
    with open(filename) as f: 
        content = f.read() 
        return dict([(i, content.count(i)) for i in SPECIAL_CHARS]) 
 
pprint(count_special_chars('example.txt')) 

示例输出:

{' ': 0, 
 '!': 2, 
 '.': 1, 
 '@': 1, 
 '[': 0, 
 '~': 0 
 # the remaining keys with a value of zero are ignored 
  ...}