我正在尝试让python计算文本文件中有多少字母或符号。我的文本文件是'*#%##'
但是由于某种原因,当我输入一个符号时,它会计算所有字符而不是输入,所以如果我输入'#'
,我得到的输出为5而不是3。 / p>
这是我到目前为止所做的:
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)
答案 0 :(得分:3)
您正在Symbol
循环中重新绑定for
:
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)
答案 1 :(得分: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)