I have been trying to define a function that gets 2 inputs (a character and a file path) and returns the amount of times the character appears in it. I know there is a shorter way to do this with the method.count but I would like to know why this function always returns 0.
def lettercount(character , path):
with open("bear.txt") as myfile:
counter = [obj for obj in myfile if obj==character]
return len(counter)
When you iterate over a file (
myfile), you get lines (obj). Soobj==characterwill only ever be true if the last line of a file ischaracterand there's no trailing newline.To iterate over characters, you can add another loop to your comprehension:
Although, you don't actually need to keep the characters themselves since you only need their count. You can use
sum()like this: