Python正则表达式删除符号之间的所有文本

2024-05-01 04:00:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一组这样的句子

"<S>Today is a <unk> sunny day and <num> children are playing outside </S>"

我想删除<;之间的所有文本&燃气轮机;符号,这样输出的句子是

"Today is a sunny day and children are playing outside"

如何使用Python中的正则表达式实现这一点


Tags: and文本lttodayisnumare句子
3条回答

我想您可以简单地搜索<&燃气轮机;符号并将字符串替换为空(“”),以便从字符串中删除这些符号

编辑:以下是我的新正则表达式示例:

RegEx101

<[^>]*>

您只需锁定“必须移除”目标,并匹配该目标,然后移除该目标

在python中

ss="""<S>Today is a <unk> sunny day and <num> children are playing outside </S>"""
regx= re.compile(r'<[^>]*>')
print(regx.sub("",ss))

输出为

Today is a  sunny day and  children are playing outside 

将我的评论转换为此处的答案

您可以使用:

import re

str = re.sub(r'\s*<[^>]*>\s*', ' ', str)

Regex\s*<[^>]*>\s*匹配一个字符串,该字符串以<开头,以>结尾,两边都有可选的空格

相关问题 更多 >