anon2000
anon2000

Reputation: 57

Function to find a string within text file (Python)

I'm trying to write a function where the input string is searched for within a text file (the text file contains a list of english words, all in lowercase). The input string may be inputted as all lowercase, uppercase or with the first letter uppercase and the rest lowercase.

So far I've got this, but it's not exactly working and I'm not sure what to do.

def is_english_word( string ):
    with open("english_words.txt", "r") as fileObject:

        if string in fileObject.read():
            return(True)

        newstring = string

        if newstring[0].isupper() == True:
            newstring == string.lower()

        if newstring in fileObject.read():
            return(True)

Upvotes: 1

Views: 6088

Answers (2)

vencaslac
vencaslac

Reputation: 2854

you have an indent issue: the with statement needs to be one indent inside def:

def is_english_word( string ):
    with open("english_words.txt", "r") as fileObject:

        if string.istitle() or string.isupper():
           return string.lower() in fileObject.read()
        else:
           return string in fileObject.read()

there is no need to check for all of the possible cases of the input string, just make it all lowercase and check for that.

Upvotes: 1

Vassily
Vassily

Reputation: 5428

Try this:

def is_english_word(string):
    with open("english_words.txt", "r") as fileObject:
        text = fileObject.read()
        return string in text or (string[0].lower() + string[1:]) in text

Upvotes: 1

Related Questions