[英]Counting specific letters or symbols in a text file in Python
I'm trying to get python to count how many of a letter or symbol that there is in a text file. 我正在尝试让python计算文本文件中有多少个字母或符号。 My text file is '*#%##'
but for some reason when I input a symbol it counts all of the characters rather than the input so I get an output of 5 rather than 3 if I for example inputted '#'
. 我的文本文件是'*#%##'
但是由于某种原因,当我输入符号时,它会计算所有字符而不是输入,因此如果输入例如'#'
,我得到的输出将是5而不是3。
This what I have done so far: 到目前为止,我所做的是:
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)
You are rebinding Symbol
in the for
loop: 您正在for
循环中重新绑定Symbol
:
for Symbol in data:
This just assigns each character in your file to Symbol
, then increments the count. 这只是将文件中的每个字符分配给Symbol
,然后增加计数。
Use str.count()
instead: 使用str.count()
代替:
with open ("words.txt", "r") as myfile:
data = myfile.read().replace('\n', '')
print(data)
freq = data.count(Symbol)
print(freq)
or, if you must use a loop, then test each character: 或者,如果必须使用循环,则测试每个字符:
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)
For a large input file, you may want to consider collections.Counter
对于较大的输入文件,您可能需要考虑使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.