[Solved] Counting occurrences of a word in a file


from pathlib import Path

def count(filename: str, word = "hello"):
    file = Path(filename)
        
    text = file.read_text()
    lines_excluding_first = text.split("\n")[1:]
    
    counts = sum([sum(list(map(lambda y: 1 if word == y else 0, x.split(" ")))) for x in lines_excluding_first])
    
    
    return counts

Example:
say you have a txt file like:

sample.txt
----------

this is the first line so this dose not count!
hello!! this is a sample text.
text which will be used as sample.
if nothing no word specified hellow is returned!
it will return the count.
print(count("sample.txt")) 
## output: 2

EDIT:

I have made a small correction in the code now "hellow!!" and "hellow" are two separate words. Words are separated by blank spaces and than checked for equality. Therefore "hellow" and “hellow.” are also different!

As per the request here is how it will look on repl.it:

make a sample.txt first:
sample.txt
main.py looks like:
main.py
you can see the output as 2 for default “hello”
[output is case sensitive i.e Hello and hello are not the same]

6

solved Counting occurrences of a word in a file