python - 检查文本文件python中是否存在单词

标签 python search

我正在使用 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")

最佳答案

最好习惯使用 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')

关于python - 检查文本文件python中是否存在单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44205923/

相关文章:

python - 如何将系列转换为数据框并对其进行透视

python - 未找到 : Container localhost does not exist when I load model with tensorflow and flask

javascript - 一次搜索多个 ng-repeats

postgresql - Postgres - 尽可能多地匹配搜索参数的开头

delphi - 计算给定路径的子目录数

python - requests.exceptions.SSLError : [Errno 8] _ssl. c:504: EOF 发生违反协议(protocol)

python - 如何消除 PyInstaller 单文件夹构建中的困惑?

python - 转换为二进制并保留前导零

java - 如何解决 replaceAll 的 replaceAll

MySQL 查询 BOOLEAN MODE 区分大小写