我有一个列表名称my= ['cbs is down','abnormal']
并且我在阅读模式下打开了一个文件
现在我想搜索列表中存在的任何可用字符串并执行 if 操作
fopen = open("test.txt","r")
my =['cbs is down', 'abnormal']
for line in fopen:
if my in line:
print ("down")
当我执行它时,我得到以下内容
Traceback (most recent call last):
File "E:/python/fileread.py", line 4, in <module>
if my in line:
TypeError: 'in <string>' requires string as left operand, not list
这应该可以解决问题:
if any(i in line for i in my):
...
基本上,您正在检查my
并检查其any
元素是否存在于行中。
fopen = open("test.txt","r")
my =['cbs is down', 'abnormal']
for line in fopen:
for x in my:
if x in line:
print ("down")
示例输入
Some text cbs is down
Yes, abnormal
not in my list
cbs is down
输出
down
down
down
错误的原因:
in
运算符,用于:
if my in line: ...
^ ^
|_ left | hand side
|
|_ right hand side
对于右侧的字符串操作数(即 line
( 需要在左侧使用相应的字符串操作数。此操作数一致性检查由 str.__contains__
方法实现,其中对 __contains__
的调用是从右侧的字符串进行的(请参阅 cpython 实现(。同:
if line.__contains__(my): ...
但是,您传递的是列表my
,而不是字符串。
解决此问题的一种简单方法是使用内置any
函数检查列表中的任何项目是否包含在当前行中:
for line in fopen:
if any(item in line for item in my):
...
或者,由于您只有两个项目,因此使用or
运算符(双关语无意(,其短路方式与any
相同:
for line in fopen:
if 'cbs is down' in line or 'abnormal' in line:
...
您还可以my
join
正则表达式(如 b(cbs is down|abnormal)b
(中的术语,并使用re.findall
或re.search
来查找术语。这样,您还可以将模式括在单词边界b...b
中,使其不匹配较长单词的部分,并且您还可以看到匹配的术语以及位置。
>>> import re
>>> my = ['cbs is down', 'abnormal']
>>> line = "notacbs is downright abnormal"
>>> p = re.compile(r"b(" + "|".join(map(re.escape, my)) + r")b")
>>> p.findall(line)
['abnormal']
>>> p.search(line).span()
(21, 29)