[英]how to count repeated characters in text file using python
我是 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
請告訴我我的代碼有什么問題?
“返回計數”中的識別問題
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"))
將您的 return 移到 for 循環之外。 它目前只經過 1 次迭代。
如果要計算給定字符在字符串(或文件)中出現的次數,可以使用 count 方法:
with open(filename) as f:
text = f.read()
print(text.count('r'))
您可以使用集合來獲取所有字符頻率的字典,並查看一個字符重復了多少次。
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})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.