replace pattern with a sequential number string in python

余生长醉 提交于 2019-12-19 03:14:14

问题


I'm trying to achieve the following replacement in python. Replace all html tags with {n} & create a hash of [tag, {n}]
Original string -> "<h> This is a string. </H><P> This is another part. </P>"
Replaced text -> "{0} This is a string. {1}{2} This is another part. {3}"

Here's my code. I've started with replacement but I'm stuck at the replacement logic as I cannot figure out the best way to replace each occurrence in a consecutive manner i.e with {0}, {1} and so on:

import re
text = "<h> This is a string. </H><p> This is another part. </P>"

num_mat = re.findall(r"(?:<(\/*)[a-zA-Z0-9]+>)",text)
print(str(len(num_mat)))

reg = re.compile(r"(?:<(\/*)[a-zA-Z0-9]+>)",re.VERBOSE)

phctr = 0
#for phctr in num_mat:
#    phtxt = "{" + str(phctr) + "}"
phtxt = "{" + str(phctr) + "}"
newtext = re.sub(reg,phtxt,text)

print(newtext)

Can someone help with a better way of achieving this? Thank you!


回答1:


import re
import itertools as it

text = "<h> This is a string. </H><p> This is another part. </P>"

cnt = it.count()
print re.sub(r"</?\w+>", lambda x: '{{{}}}'.format(next(cnt)), text)

prints

{0} This is a string. {1}{2} This is another part. {3}

Works for simple tags only (no attributes/spaces in tags). For extended tags, you have to adapt the regexp.

Also, not reinitializing cnt = it.count() will keep the numbering going on.

UPDATE to get a mapping dict:

import re
import itertools as it

text = "<h> This is a string. </H><p> This is another part. </P>"

cnt = it.count()
d = {}
def replace(tag, d, cnt):
    if tag not in d:
        d[tag] = '{{{}}}'.format(next(cnt))
    return d[tag]
print re.sub(r"(</?\w+>)", lambda x: replace(x.group(1), d, cnt), text)
print d

prints:

{0} This is a string. {1}{2} This is another part. {3}
{'</P>': '{3}', '<h>': '{0}', '<p>': '{2}', '</H>': '{1}'}


来源:https://stackoverflow.com/questions/13622517/replace-pattern-with-a-sequential-number-string-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!