user3469594
user3469594

Reputation: 3

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. 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 '#'.

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)

Upvotes: 0

Views: 6251

Answers (2)

Adam Smith
Adam Smith

Reputation: 54213

For a large input file, you may want to consider 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)

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1122092

You are rebinding Symbol in the for loop:

for Symbol in data:

This just assigns each character in your file to Symbol, then increments the count.

Use str.count() instead:

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)

Upvotes: 4

Related Questions