遍历具有多个条件的所有行

Iterating through all lines with multiple conditions

我想一次遍历所有行并检查字符串是否在任何行中,如果是则应用函数并跳出循环,如果不是则检查第二个字符串并执行同一件事情。如果在任何一行中都没有找到字符串,则继续执行其他操作..

split= text.as_string().splitlines()
for row in split:
   if 'Thanks Friend' in row.any():
     apply_some_function()
     break
   elif 'other text' in row.str.any():
     apply_some_function()
     break
   else:
     .......

我一直收到错误消息:


AttributeError                            Traceback (most recent call last)
      <ipython-input-179-8f0e09f62771> in <module>()
      1 for row in split:
      2 
----> 3   if 'Thanks Friend' in row.str.any():
      4     apply_some_function()
      5     break

AttributeError: 'str' object has no attribute 'str'

尝试以下操作。但请记住,文本将在 return 处拆分,这可能不是您想要的。此外,如果 'other text' 处于拆分状态,您是否想做一些不同的事情?如果你这样做,那么你需要告诉我们。

split = text.split("\n")
if any(x for x in split if 'Thanks Friend' in x):
    apply_some_function()
elif any(x for x in split if 'other text' in x):
    apply_some_function()
else:
    pass

您还可以这样做:

if any(x for x in split if 'Thanks Friend' in x) or \:
any(x for x in split if 'other text' in x):
    apply_some_function()

您正在使用 python 中不存在的对象的属性/方法。这就是 AttributeError 的意思。

查找对象所有现有属性的一种方法是使用 python 控制台中的函数 help()。例如,键入 help(str) 以获取可用于字符串的所有方法。

当您想在每一行上做不同的事情时,我认为没有一种方法可以转到所有行 "at once"。所以你必须保留你的原始代码。这是它的固定版本:

split = text.splitlines()
for row in split:
    if 'Thanks Friend' in row:
        apply_some_function()
        break
    elif 'other text' in row:
        apply_some_function()
     break
   else:
       ...