我可以传递给 .replace 函数的字符串中是否有多个字符的通配符?

Is there a wildcard for multiple characters in a string that I can pass to the .replace function?

我正在从 json 文件中读取某些值并将该数据写入新文件。最终目标是将 .json 翻译成 .yml 文件(有超过 350k 个文件,所以我不能把它放在在线翻译器中)。

在执行此操作时,我将从数据中删除“<'tags'>”。我一直在使用 .replace 函数来编写没有不需要的子字符串的新字符串。

因为我只对删除以“<”开头并以“>”结尾的字符串感兴趣,所以我想知道是否有通配符,例如 * 或 .这将在 .replace 函数中起作用。

这是我的代码:

with open('example' + '.txt') as json_data:
data=json.load(json_data)
for r in data['posts']:
    fo = open(str(r['no'])+".txt","w")
    resp = "--" + r['com']
    resp=resp.replace("<br>","")
    resp=resp.replace('<span class="quote">&gt;','')
    resp=resp.replace('</span>','')
    resp=resp.replace('<span>','')
    fo.write(resp)
    fo.close()

欢迎来到堆栈溢出。

您可以使用正则表达式,在 re 模块的 python 中实现。

import re
regexp = re.compile(r"<.*>")
regexp.sub("", text)

用空字符串替换 <> 之间的所有内容。

可能的解决方案:

import re
re.sub('(<\S[^<]*>)', '', text)

#Examples
text1 = '</span> something <span>'
re.sub('(<\S[^<]*>)', '', text1)
#' something '

text2 = '<span class="quote">'
re.sub('(<\S[^<]*>)', '', text2)
#''