在Python中计算文本文件中特定字母或符号
我正在尝试让Python计算一个文本文件中某个字母或符号出现的次数。我的文本文件内容是'*#%##'
,但不知为什么,当我输入一个符号时,它却把所有字符都算上了,所以如果我输入'#'
,输出的结果是5,而不是3。
这是我到目前为止所做的:
Symbol = input("Pick a Symbol ")
freq = 0
with open ("words.txt", "r") as myfile:
data = myfile.read().replace('\n', '')
print(data)
for Symbol in data:
freq = (freq + 1)
print(freq)
2 个回答
1
对于一个很大的输入文件,你可能想要考虑使用 collections.Counter
这个工具。
from collections import Counter
def countsymbols(filename,symbols):
"""Counts the symbols in `filename`.
`symbols` is an iterable of symbols"""
running_count = Counter()
with open(filename) as f:
for line in f:
running_count += Counter(line.strip())
return {key:value for key,value in running_count.items() if key in symbols}
symbols = map(str.strip,input("Enter symbols: ").split())
filename = input("Filename: ")
symbolcount = countsymbols(filename,symbols)
4
你在 for
循环里重新定义了 Symbol
:
for Symbol in data:
这段代码只是把文件里的每个字符都赋值给 Symbol
,然后计数加一。
建议使用 str.count()
方法,这样更简单:
with open ("words.txt", "r") as myfile:
data = myfile.read().replace('\n', '')
print(data)
freq = data.count(Symbol)
print(freq)
或者,如果你非得用循环的话,那就逐个检查每个字符:
with open ("words.txt", "r") as myfile:
data = myfile.read().replace('\n', '')
print(data)
freq = 0
for char in data:
if char == Symbol:
freq = freq + 1
print(freq)