![](/img/trans.png)
[英]How to add space before and after specific character using regex in Python?
[英]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.