python - 字符串中是否有可以传递给 .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">>','')
resp=resp.replace('</span>','')
resp=resp.replace('<span>','')
fo.write(resp)
fo.close()
解决方案
欢迎来到堆栈溢出。
您可以使用正则表达式,在re
模块中的 python 中实现。
import re
regexp = re.compile(r"<.*>")
regexp.sub("", text)
用空字符串替换 <> 之间的所有内容。
推荐阅读
- c# - 如何在 .NET 中制造一个空字符串?
- javascript - 如何使用 JavaScript Promise 访问函数外的变量
- spring - 在 Spring Flux 应用程序中获取经过身份验证的用户名作为 spring
- javascript - 检查元素是否重叠的最高效方法
- csvhelper - csvhelper 和 html 标记的编码问题
- node.js - 文件未从 Angular 发送到 Nodejs
- python - 无法复制 POST 请求
- django - 我应该使用 Django 还是 Nginx 来提供静态图像文件?它们的文件路径是由 Django 生成的吗?
- php - 如何从另一个文件php验证mysql数据库连接
- ios - Xcode 不断提供 .signUp 仅在 iOS 13.2 中可用。这是一些 Xcode 错误吗?