[英]Python - Search Text File For Any String In a List
Apologies is this is against the rules. 抱歉,这是违反规则的。 I have tried creating a simple Python script that searches a text file for any of the strings in a list.
我尝试创建一个简单的Python脚本,该脚本在文本文件中搜索列表中的任何字符串。
KeyWord =['word', 'word1', 'word3']
if x in Keyword in open('Textfile.txt').read():
print('True')
When i'm running the code I am getting a "name error: name 'x' is not defined" although i'm not sure why? 当我运行代码时,尽管我不确定为什么会出现“名称错误:未定义名称'x'”的问题?
x
is not defined. x
未定义。 You forgot the loop that would define it. 您忘记了定义它的循环。 This will create a generator so you will need to consume it with
any
: 这将创建一个生成器,因此您将需要使用
any
生成器:
KeyWord =['word', 'word1', 'word3']
if any(x in open('Textfile.txt').read() for x in KeyWord):
print('True')
This works but it will open and read the file multiple times so you may want 此方法有效,但是它将多次打开并读取文件,因此您可能需要
KeyWord = ['word', 'word1', 'word3']
file_content = open('test.txt').read()
if any(x in file_content for x in KeyWord):
print('True')
This also works, but you should prefer to use with
: 这也适用,但你应该更喜欢使用
with
:
KeyWord = ['word', 'word1', 'word3']
with open('test.txt') as f:
file_content = f.read()
if any(x in file_content for x in KeyWord):
print('True')
All of the above solutions will stop as soon as the first word in the list is found in the file. 一旦在文件中找到列表中的第一个单词,以上所有解决方案都将停止。 If this is not desireable then
如果这是不希望的,那么
KeyWord = ['word', 'word1', 'word3']
with open('test.txt') as f:
file_content = f.read()
for x in KeyWord:
if x in file_content:
print('True')
You could do this with a for loop as below. 您可以使用for循环执行此操作,如下所示。 The issue with your code is it does not know what
x
is. 您的代码的问题是它不知道
x
是什么。 You can define it inside of the loop to make x
equal to a value in the KeyWord
list for each run of the loop. 您可以在循环内部定义它,以使
x
等于每次循环运行在KeyWord
列表中的值。
KeyWord =['word', 'word1', 'word3']
with open('Textfile.txt', 'r') as f:
read_data = f.read()
for x in KeyWord:
if x in read_data:
print('True')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.