【发布时间】: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
请告诉我我的代码有什么问题?
【问题讨论】:
-
您的
return在for循环内,因此它在第一个字符处停止 -
len(text) 返回字符串的字符数
-
Jalo,目标不是计算总字符数,而是计算 e.g. “a”或“b”
-
@GoutamReddy:不是发帖,谁解决了这个问题,最好在 StackOverflow 上接受答案。这是通过点击勾号来完成的。由于多个答案可能是正确的,因此请尝试找出哪一个最能解释解决方案。
标签: python string text count analyzer