2017-10-13 125 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 
相關問題