Search code examples
pythonfiletextline

How to check if a variable is the same as a line in a txt file - python


def check(file_name, string_to_search):
    with open(file_name, 'r') as read_obj:
        for line in read_obj:
            if string_to_search in line:
                return True
    return False

while True:
    word = input('Is the word positive? | ')
    if check('positivewords.txt', word):
        print('Word is positive')
    elif check('negativewords.txt', word):
        print('Word is negative')
    else:
        print('Word not in database')

the code is supposed to read the txt file line by line and determine if the 'word' variable is exactly equal to one of those lines. the problem is that whenever it runs, the variable doesn't have to be exactly equal. for example, say one of the lines is 'free', and I search 'e', it will still pop up that it's in the txt file. thanks in advance.


Solution

  • The problem in your code is this line:

    if string_to_search in line:
    

    which will be true if the string occurs anywhere in line. It doesn't match against a whole word. I think that's what you want to do?

    What you can do is break up each line into a list of words. The split() method of the string class can do that. If your line contains punctuation characters you would have remove them too for comparison with your search string; for that you can use the string's strip() method. Putting it all together your check() function becomes:

    import string
    
    def check(file_name, string_to_search):
        with open(file_name, 'r') as read_obj:
            for line in read_obj:
                #List of words (without punctuation)
                words = [word.strip(string.punctuation) for word in line.split()]
                if string_to_search in words:
                    return True
        return False