Search code examples
pythonsplitcase-sensitive

reading a text file and counting how many times a word is repeated. Using .split function. Now wants it to ignore case sensitive


Getting the desired output so far.

The program prompts user to search for a word.

user enters it and the program reads the file and gives the output.

'ashwin: 2'

Now i want it to ignore case sensitive. For example, "Ashwin" and "ashwin" both shall return 2, as it contains two ashwin`s in the text file.

def word_count():
    file = "test.txt"
    word = input("Enter word to be searched:")
    k = 0

    with open(file, 'r') as f:
        for line in f:
            words = line.split()
            for i in words:
                if i == word:
                    k = k + 1
    print(word + ": " + str(k))


word_count()

Solution

  • You could use lower() to compare the strings in this part if i.lower() == word.lower():

    For example:

    def word_count():
        file = "test.txt"
        word = input("Enter word to be searched:")
        k = 0
    
        with open(file, 'r') as f:
            for line in f:
                words = line.split()
                for i in words:
                    if i.lower() == word.lower():
                        k = k + 1
        print(word + ": " + str(k))
    
    
    word_count()