检查文本文件python中是否存在单词 [英] checking if word exists in a text file python
本文介绍了检查文本文件python中是否存在单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 Python,我正在尝试找出文本文件中是否包含某个单词.我正在使用此代码,但它总是打印找不到单词",我认为该条件存在一些逻辑错误,如果您可以更正此代码,请任何人:
I'm working with Python, and I'm trying to find out if a word is in a text file. i am using this code but it always print the "word not found", i think there is some logical error in the condition, anyone please if you can correct this code:
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
在另一个字符串中搜索一个字符串.
Better you should become accustomed to using with
when you open a file, so that it's automatically close when you've done with it. But the main thing is to use in
to search for a string within another string.
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中是否存在单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文