gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:14:02 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com