【问题标题】:how to count repeated characters in text file using python如何使用python计算文本文件中的重复字符
【发布时间】:2016-11-17 16:01:18
【问题描述】:

我是python的初学者,我正在尝试用python制作一个小程序来计算文本文件中的重复字符

这里是代码

import string 

def count_char(text,char):
    count = 0
    for c in text:
        if c == char:
            count +=1
        return count

filename = raw_input("Enter File name:")
with open(filename) as f:
    text=f.read()

print(count_char(text,"r"))

但它将输出打印为

>> 0

请告诉我我的代码有什么问题?

【问题讨论】:

  • 您的returnfor 循环内,因此它在第一个字符处停止
  • len(text) 返回字符串的字符数
  • Jalo,目标不是计算总字符数,而是计算 e.g. “a”或“b”
  • @GoutamReddy:不是发帖,谁解决了这个问题,最好在 StackOverflow 上接受答案。这是通过点击勾号来完成的。由于多个答案可能是正确的,因此请尝试找出哪一个最能解释解决方案。

标签: python string text count analyzer


【解决方案1】:

“返回计数”中的识别问题

def count_char(text, char):
    count = 0
    text = list(text)
    for c in text:
        if c == char:
            count += 1
    return count


filename = raw_input("Enter File name:")
with open(filename) as f:
    text = f.read()

print(count_char(text, "r"))

【讨论】:

    【解决方案2】:

    将您的 return 移到 for 循环之外。目前只进行了 1 次迭代。

    【讨论】:

    • 为什么不超过 3621?
    • 您可能想要更改它,以便您执行 readline 并计算每一行,而不是读取整个文件。这可能是记忆的事情。 filename = raw_input("输入文件名:") count = 0 with for open(filename) as f: for line in f: count += count_char(line, 'r') print(count)
    【解决方案3】:

    如果要计算给定字符在字符串(或文件)中出现的次数,可以使用 count 方法:

    with open(filename) as f:
        text = f.read()
        print(text.count('r'))
    

    【讨论】:

      【解决方案4】:

      您可以使用集合来获取所有字符频率的字典,并查看一个字符重复了多少次。

      from collections import Counter
      with open(file) as f:
          c = Counter()
          for x in f:
              c += Counter(x.strip())
      

      示例:数据会这样存储:

      Counter({'a': 3, ' ': 3, 'c': 3, 'b': 3, 'e': 3, 'd': 3, 'g': 3, 'f': 3})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-28
        • 2018-03-09
        • 2016-03-08
        • 1970-01-01
        • 2017-08-14
        • 1970-01-01
        相关资源
        最近更新 更多