gpt4 book ai didi

python - 计算文件中的每个字符

转载 作者:太空宇宙 更新时间:2023-11-04 06:53:03 25 4
gpt4 key购买 nike

我正在尝试计算文件中的每个字符并将其放入字典中。但这不太奏效,我没有得到所有字符。

#!/usr/bin/env python
import os,sys

def count_chars(p):
indx = {}
file = open(p)

current = 0
for ch in file.readlines():
c = ch[current:current+1]
if c in indx:
indx[c] = indx[c]+1
else:
indx[c] = 1
current+=1
print indx

if len(sys.argv) > 1:
for e in sys.argv[1:]:
print e, "contains:"
count_chars(e)
else:
print "[#] Usage: ./aufg2.py <filename>"

最佳答案

假设您正在计算的文件适合内存:

import collections
with open(p) as f:
indx = collections.Counter(f.read())

否则,您可以一点一点地阅读它:

import collections
with open(p) as f:
indx = collections.Counter()
buffer = f.read(1024)
while buffer:
indx.update(buffer)
buffer = f.read(1024)

关于python - 计算文件中的每个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14176421/

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