Python3根据标签类型的条件替换标签

2024-09-26 22:50:28 发布

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

我希望文本中看起来像<Bus:1234|Bob Alice><Car:5678|Nelson Mandela>的所有标记分别替换为<a my-inner-type="CR:1234">Bob Alice</a><a my-inner-type="BS:5678">Nelson Mandela</a>。所以基本上,根据类型是TypeA还是TypeB,我想用Python3和regex相应地替换文本字符串中的文本。你知道吗

我尝试用python执行以下操作,但不确定这是否是正确的方法:

import re
def my_replace():
    re.sub(r'\<(.*?)\>', replace_function, data)

在上面,我尝试对< >标记和找到的每个标记执行regex,然后将其传递给一个名为replace_function的函数,在标记之间分割文本,确定它是TypeA还是TypeB,并计算内容并动态返回替换标记。我甚至不确定使用re.sub是否可以这样做,但任何线索都会有所帮助。非常感谢。你知道吗

示例:

  • <Car:1234|Bob Alice>变成<a my-inner-type="CR:1234">Bob Alice</a>

  • <Bus:5678|Nelson Mandela>变成<a my-inner-type="BS:5678">Nelson Mandela</a>


Tags: 标记文本rebsmytypecarreplace
3条回答

抱歉,这不是一个完整的答案,但我在电脑前睡着了,但这是正则表达式,它将匹配您提供的任何字符串(<Type)(\w:)(\d+\|)(\w+\s\w+>)。查看https://pythex.org/测试您的正则表达式。你知道吗

可能是@swalladge答案的扩展,但这里我们使用字典的优势,如果我们知道映射的话。(请考虑使用自定义映射函数替换字典。你知道吗

import re    

d={'TypeA':'A',
   'TypeB':'B',
   'Car':'CR',
   'Bus':'BS'}

def repl(m):
  return '<a my-inner-type="'+d[m.group(1)]+m.group(2)+'">'+m.group(3)+'</a>'

s='<TypeA:1234|Bob Alice> or <TypeB:5678|Nelson Mandela>'
print(re.sub('<(.*?)(:\d+)\|(.*?)>',repl,s))
print()
s='<Bus:1234|Bob Alice> or <Car:5678|Nelson Mandela>'
print(re.sub('<(.*?)(:\d+)\|(.*?)>',repl,s))

输出

<a my-inner-type="A:1234">Bob Alice</a> or <a my-inner-type="B:5678">Nelson Mandela</a>

<a my-inner-type="BS:1234">Bob Alice</a> or <a my-inner-type="CR:5678">Nelson Mandela</a>

工作示例here。你知道吗


正则表达式 我们在3个组中捕获我们需要的内容,并通过match object引用它们。粗体突出显示的是我们在regex中捕获的3个组。
<(.*?)(:\d+)\|(.*?)>
我们在repl函数中使用这3个组来返回正确的字符串。你知道吗

这在re.sub中是完全可能的,并且使用替换函数(设计为允许动态替换)是正确的。请参阅下面的示例,了解与您给出的示例一起工作的示例-可能需要根据文本中存在的其他数据(即需要忽略的其他标记)进行修改以适合您的用例

import re

def replace_function(m):
    # note: to not modify the text (ie if you want to ignore this tag),
    # simply do (return the entire original match):
    # return m.group(0)

    inner = m.group(1)
    t, name = inner.split('|')

    # process type here - the following will only work if types always follow
    # the pattern given in the question
    typename = t[4:]
    # EDIT: based on your edits, you will probably need more processing here
    # eg:
    if t.split(':')[0] == 'Car':
        typename = 'CR'
    # etc

    return '<a my-inner-type="{}">{}</a>'.format(typename, name)

def my_replace(data):
    return re.sub(r'\<(.*?)\>', replace_function, data)



# let's just test it
data = 'I want all the tags in a text that look like <TypeA:1234|Bob Alice> or <TypeB:5678|Nelson Mandela> to be replaced with'
print(my_replace(data))

警告:如果此文本实际上是完整的html,正则表达式匹配将不可靠-请使用类似beautifulsoup的html处理器。;)

相关问题 更多 >

    热门问题