gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:18 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com