简体   繁体   English

如何使用正则表达式循环在特定字符之前和之后过滤句子的一部分

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

'I want to extract the text before & after ":" and "|" '我想提取“:”和“ |”之前和之后的文本 using regex and seperate it into speaker and title. 使用正则表达式并将其分成演讲者和标题。

'There are many such sentences so I need to write a 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 you are willing to use plain string functions instead of regex: 如果您愿意使用纯字符串函数而不是正则表达式:

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

使用正则表达式

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

you can use this simple regex '.[:|].' 您可以使用此简单的正则表达式'.[:|].' ,

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)

output: 输出:

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

note the last one :) 注意最后一个:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Python中使用正则表达式在特定字符之前和之后添加空格? - How to add space before and after specific character using regex in Python? 在熊猫中的特定字符后删除句子的一部分 - Remove part of a sentence after specific character in Pandas 如何使用正则表达式解析句子 - How do I parse a sentence using regex 如何检查句子特定部分之前的字符串是否与其他行中的任何文本匹配或不匹配(与特定部分之后相同)? - how to check whether the string before specific part of a sentence matches with any of the text in other lines or no (same with after specific part)? 如何更改句子中字符的位置? - How do I change the location of a character in a sentence? 如何在正则表达式中的预期搜索字符串之前或之后添加条件以搜索特定子字符串? - How do I add conditions to search for specific substrings before or after intended string of search in regex? 在Python中使用regex消除输出循环中特定字符之前的所有文本 - Eliminate all text before specific character in output loop using regex in Python 如何使用正则表达式在出现字符串后替换特定字符 - How to replace a specific character after the occurrence of a string using regex 如何在列中选择特定值并在之前添加字符 - How do I select specific values in column and add character before 如何使用正则表达式在Python 3中查找特定字符串之后或之前的行? - How to find a line after or before a specific string in Python 3 using regex?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM