我正在尝试在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)
有人可以提供更好的方法来实现这一目标吗?谢谢!
我试图以下面的方式分割字符串.这是一个示例字符串:
"Hello this is a string.?-2.34 This is an example1 string."
Run Code Online (Sandbox Code Playgroud)
请注意,""是U + F8FF unicode字符,字符串的类型是Unicode.
我想打破字符串:
"Hello this is a string.","-2.34"," This is an example1 string."
Run Code Online (Sandbox Code Playgroud)
我写了一个正则表达式来分割字符串,但使用这个我不能得到我想要的数字部分.(第一个字符串中的-2.34)
我的代码:
import re
import os
from django.utils.encoding import smart_str, smart_unicode
text = open(r"C:\data.txt").read()
text = text.decode('utf-8')
print(smart_str(text))
pat = re.compile(u"\uf8ff-*\d+\.*\d+")
newpart = pat.split(text)
firstpart = newpart[::1]
print ("first part of the string ----")
for f in firstpart:
f = smart_str(f)
print ("-----")
print f
Run Code Online (Sandbox Code Playgroud)