簡體   English   中英

如何使用正則表達式循環在特定字符之前和之后過濾句子的一部分

[英]How do I filter a part of sentence before and after a specific character using regex an loop

'我想提取“:”和“ |”之前和之后的文本 使用正則表達式並將其分成演講者和標題。

“這樣的句子很多,所以我需要寫一個循環”

 text1='If I controlled the internet | Rives '
 text2='Life at 30,000 feet | Richard Brandson'
 text3='larry brilliant : A surprising idea for "solving" climate change'

如果您願意使用純字符串函數而不是正則表達式:

if '|' in text:
    title, speaker = text.split('|', 1)
elif ':' in text:
    speaker, title = text.split(':', 1)

使用正則表達式

re.compile('[\s]*[|:][\s]*').split(text)

您可以使用此簡單的正則表達式'.[:|].'

import re
text1='If I controlled the internet | Rives '
text2='Life at 30,000 feet | Richard Brandson'
text3='larry brilliant : A surprising idea for "solving" climate change'

text = (text1, text2, text3)

for item in text:
    title, speaker = re.split('.[:|].', item)
    print('title:', title, ' - Speaker:', speaker)

輸出:

title: If I controlled the internet  - Speaker: Rives 
title: Life at 30,000 feet  - Speaker: Richard Brandson
title: larry brilliant  - Speaker: A surprising idea for "solving" climate change

注意最后一個:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM