如何检查变量是否与 txt 文件中的一行相同 - python

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')

代码应该逐行读取 txt 文件并确定 'word' 变量是否正好等于其中一行。问题是无论何时运行,变量都不必完全相等。例如,假设其中一行是 'free',我搜索 'e',它仍然会弹出它在 txt 文件中。提前致谢。

in,正如它所说,检查对象是否在另一个对象中。这包括字符串中的一个字符。您应该使用 == 表示完全等于*.

def check(file_name, string_to_search):
    with open(file_name, 'r') as read_obj:
        for line in read_obj:
            if string_to_search.lower() == line.lower():  # <-- Changed in to == and made them lower
                return True
    return False

*。好吧,不完全是。有点难以解释。 == returns True 如果对象的值相等,但这并不意味着它们具有相同的类型。如果要检查它们是否是同一类型,请使用 is.

如果有人比我聪明编辑我的问题以澄清我上面的胡言乱语,我将不胜感激。

您的代码中的问题是这一行:

if string_to_search in line:

如果字符串出现在 line 中的任何位置,则为真。它与整个单词不匹配。我想这就是你想要做的?

您可以将每一行分成一个单词列表。字符串 class 的 split() 方法可以做到这一点。如果您的行包含标点符号,您也可以删除它们以便与您的搜索字符串进行比较;为此,您可以使用字符串的 strip() 方法。将它们放在一起,您的 check() 函数变为:

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