将分号替换为python中同一行中的单词



我想要像<Prags>87654321</Prags>这样的数据,<Cookie>2476157</Cookie><Guddu>98765</Guddu>我的数据类似<Prags>87654321;将分号替换为句子的第一个单词。

给定您的信息,我假设您有一个包含要处理的信息的文件或多行字符串。如果您的多行字符串如下所示:

data = """
<Prags>87654321;
<Cookie>87654321;
<Guddu>87654321;
<Prags>87654321;
<Prags>87654321;"""

我会将这个字符串拆分为单独的行,并使用re提取标签,如下所示:

# extracting lines
lines = data.splitlines()
# this function looks for tags
# if there are no tags, it returns empty string

def find_tag(line):
try:
return re.match("<[^>]*>", line).group()
except AttributeError:
return ""

# we then iterate over lines and process them
for line in lines:
line = line.replace(";", find_tag(line))
print(line)

不要忘记用import re导入re包。