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

标签 python

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

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

相关文章:

python - 如何使用新列中重叠项目的输出映射两个数据框?

python - AttributeError: 模块 'datetime' 没有属性 'time'

python - 使用 pyparsing (latex) 解析嵌套组(带引号的字符串)

python - 使用 Carla 创建超车(硬编码)场景

python - 在 PostgreSQL 上使用 CTE() 进行 SQLAlchemy 查询

python - 完全独立的虚拟环境

python - 基于稀疏信息填充数组

python - 未实现错误: Layer ModuleWrapper has arguments in `__init__` and therefore must override `get_config`

python - 无法为 cartopy linux 安装 Proj 8.0.0

python - 在 Python 中检测是否使用系留电话连接到互联网