【问题标题】:How to check if a variable is the same as a line in a txt file - python如何检查变量是否与txt文件中的一行相同 - python
【发布时间】:2020-07-18 03:18:10
【问题描述】:
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”变量是否完全等于这些行之一。问题是,无论何时运行,变量都不必完全相等。例如,假设其中一行是“免费”,我搜索“e”,它仍然会弹出它在 txt 文件中。提前致谢。

【问题讨论】:

    标签: python file text line


    【解决方案1】:

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

    if string_to_search in line:
    

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

    您可以做的是将每一行分解成一个单词列表。字符串类的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
    

    【讨论】:

      【解决方案2】:

      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
      

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

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

      【讨论】:

      • 现在每当我输入任何内容时,它都会返回“word not in database”
      • @astrosts05 我没有计算大写。我编辑了答案,将数据库中的搜索查询和单词小写。
      猜你喜欢
      • 1970-01-01
      • 2019-01-06
      • 2020-04-30
      • 2022-11-03
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 2020-11-15
      • 1970-01-01
      相关资源
      最近更新 更多