Skip to main content
 首页 » 编程设计

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

2025年05月04日9Free-Thinker

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

#!/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)