2017-10-13 121 views
1

我遇到了问题,我试图从包含子字符串存在的行后面提取行。提取所有行,包括包含子字符串和Python中的子字符串后面的行的行

s=""" 
    This is so awesome 
    I need to do this more often 
    This forum rocks 
    Help me 
    """ 

如果我搜索的字符串是论坛,我想用下面的语句

s.lower().split("forum",1)[1] 

得到的结果

this forum rocks 
    Help me 

我想和我的输出是

forum rocks 

任何帮助表示赞赏。

+1

**暗示:**第一,尽量找到包含单词论坛的*行*。 – wim

+0

线条中有隐藏的“\ n”吗? – pstatix

回答

1

re.search()功能单行溶液:

import re 

s=""" 
    This is so awesome 
    I need to do this more often 
    This forum rocks 
    Help me 
    """  
result = re.search(r'.*\bforum[\s\S]*', s, re.M).group() 
print(result) 

输出:

This forum rocks 
    Help me 
+0

根据你的答案继续下去,这个解决方案还可以用于在线“论坛”之前删除文本? – ayushman999

+0

@ ayushman999,你是什么意思? – RomanPerekhrest

+0

我现在试图提取包含单词“论坛”的行上方的行。例子 - 输出将只包含“这是如此真棒我需要更频繁地这样做” – ayushman999

1

您需要逐行分割字符串,然后在每行中搜索所需的单词。

s=""" 
This is so awesome 
I need to do this more often 
This forum rocks 
Help me 
""".split('\n') 
for line in range(len(s)): 
    if "forum" in s[line]: 
     print(s[line]) 
     print(s[line+1]) 

只要多行字符串与在其文本的最后一行的下一行结束后,你就不会出界的名单。如果您的上一行有""",请在Help me旁边进行范围检查。

编辑:重新阅读这个问题。你想要所有行之后找到这个词的论坛?前面我给出的例子只是让你获得下一个一行。对于发现的关键词毕竟线,使用:

s=""" 
This is so awesome 
I need to do this more often 
This forum rocks 
Help me 
""".split('\n') 
found = False 
for line in range(len(s-1)): 
    if "forum" in s[line] or found: 
     print(s[line]) 
     found = True 

len(s-1)部分是可选的。取决于您是否希望结果中包含尾部空白行。如果你想要最后一个空白行,只需将其更改回len(s)即可。

1

试试这个,它适用于包含任意行数的字符串。

s=""" 
    This is so awesome 
    I need to do this more often 
    This forum rocks 
    Help me 
    """ 
s=s.split('\n') 
c=0 
for i in s: 
    if i.find("forum")!=-1: # no match, find returns -1 
     print "\n".join(s[c:]) 
    c+=1 

输出:

This forum rocks 
Help me 

所以,基本上你会发现在数组中的索引,其中,你的对手已经发现并在那之后返回的一切(经用\n加盟就像在的情况下原始字符串)。

1
l = s.split('\n') 
for n, str in enumerate(l): 
    if 'forum' in str: 
     print ('\n'.join(l[n:])) 
     break 

输出:

This forum rocks 
    Help me 
相关问题