【问题标题】:checking if word exists in a text file python检查文本文件python中是否存在单词
【发布时间】:2026-01-01 08:15:02
【问题描述】:

我正在使用 Python,并试图找出一个单词是否在文本文件中。我正在使用此代码,但它总是打印“找不到单词”,我认为条件中存在一些逻辑错误,如果您可以更正此代码,请任何人:

file = open("search.txt")
    print(file.read())
    search_word = input("enter a word you want to search in file: ")
    if(search_word == file):
        print("word found")
    else:
        print("word not found")

【问题讨论】:

  • 文件中的search_word,不等于文件。
  • print(file.read()) 将文件内容读入字符串,打印出来,然后丢弃。你不想那样做。您需要保存文件数据,例如data = file.read()。您应该阅读 Python 的 in 运算符。
  • @zhenguoli 那么正确的条件应该是什么?

标签: python search


【解决方案1】:

您最好习惯在打开文件时使用with,以便在您完成文件后自动关闭。但主要是使用in 在另一个字符串中搜索一个字符串。

with open('search.txt') as file:
    contents = file.read()
    search_word = input("enter a word you want to search in file: ")
    if search_word in contents:
        print ('word found')
    else:
        print ('word not found')

【讨论】:

    【解决方案2】:

    之前,您在文件变量中进行搜索,即“open("search.txt")”,但由于它不在您的文件中,因此您得到了 word not found。

    您还询问搜索词是否与“open("search.txt")”完全匹配,因为 ==。不要使用 ==,而是使用“in”。试试:

    file = open("search.txt")
    strings = file.read()
    print(strings)
    search_word = input("enter a word you want to search in file: ")
    if(search_word in strings):
        print("word found")
    else:
        print("word not found")
    

    【讨论】:

      【解决方案3】:

      其他选择,您可以在读取文件本身时search

      search_word = input("enter a word you want to search in file: ")
      
      if search_word in open('search.txt').read():
          print("word found")
      else:
          print("word not found")
      

      要缓解可能的内存问题,请使用mmap.mmap(),此处已回答related question

      【讨论】: