Ans*_*Ans 5 python replace sequential
我正在尝试在python中实现以下替换。用{n}替换所有html标记并创建[tag,{n}]的哈希值。
原始字符串->“ <h>这是一个字符串。</H><P>这是另一部分。</P>”
替换后的文本->“ {0}这是一个字符串。 1} {2}是另一部分。{3}”
这是我的代码。我从替换开始,但是由于无法确定以连续方式替换每次出现的最佳方法(例如,用{0},{1}等),所以我陷入了替换逻辑中:
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)
Run Code Online (Sandbox Code Playgroud)
有人可以提供更好的方法来实现这一目标吗?谢谢!
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)
Run Code Online (Sandbox Code Playgroud)
版画
{0} This is a string. {1}{2} This is another part. {3}
Run Code Online (Sandbox Code Playgroud)
仅适用于简单标签(标签中没有属性/空格)。对于扩展标签,您必须调整正则表达式。
同样,不重新初始化cnt = it.count()将使编号继续进行。
更新以获取映射字典:
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
Run Code Online (Sandbox Code Playgroud)
印刷品:
{0} This is a string. {1}{2} This is another part. {3}
{'</P>': '{3}', '<h>': '{0}', '<p>': '{2}', '</H>': '{1}'}
Run Code Online (Sandbox Code Playgroud)