首页 > 解决方案 > 字符串中是否有可以传递给 .replace 函数的多个字符的通配符?

问题描述

我正在从 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()

标签: pythonstringreplacesubstringwildcard

解决方案


欢迎来到堆栈溢出。

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

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

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


推荐阅读