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

标签 python string python-3.x

我正在努力编写一个 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
  ...}

关于Python:计算文件行中一组特定字符的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32281554/

相关文章:

java - 如何给java足够的时间给变量赋值?

python-3.x - 在 Matplotlib 的插图中使用 twiny()

python-3.x - Scrapy爬取蜘蛛不下载文件?

python - 在python中通过继承创建自定义float类

python - 导入错误 : cannot import name saxexts

python - Vim Flake8 忽略项目配置文件

c - 为什么我的回文检查函数总是对回文返回 false?

c# - 匹配大文本文件中的字符串?

python - 尝试在详细 View 中覆盖模板名称时出现 TemplateDoesNotExist

python - 在 python 中从 S3 加载 npy 文件