【问题标题】:Python: Replace an escaped quote with another characterPython:用另一个字符替换转义的引号
【发布时间】:2020-02-24 11:00:49
【问题描述】:

我有一个包含 HTML 的 JSON,我需要使其可解析。 Pandas 无法导入这种 JSON。

text = """[{
   "article_id": 3540349,
   "site_id": 1563,
   "domain": "https:\/\/ear.rt.hm",
   "code": "wta-jurmala-benara-u-ctrtl",
   "uri": "https:\/\/ar.rl.hq\/spormala-berera-u-cetinalu\/",
   "content_type": {
       "id": 1,
       "name": "article"
   },
   "article_type": {
       "id": 1,
       "name": "article"
   },
   "created": "2019-07-25 23:58:20",
   "modified": "2019-07-25 23:59:19",
   "publish_date": "2019-07-25 23:58:00",
   "active": true,
   "author": "<a href=\"https:\/\/spt02.com\" target=\"_blank\">I 
Kapri<\/a>"
}]"""

text = text.replace('\"', "'")

结果是(不管文字差异):

'author': '<a href='https:\/\/spo.hq' target='_blank'>Iv<\/a>'

当我尝试替换 '\"' 时,我得到:

"author": "<a href="https:\/\/spr.hq" target="_blank">Ilari<\/a>"

这又不是我想要的。

有谁知道如何正确地将 \" 转义为 ' ?

【问题讨论】:

  • \""""" 常规字符串文字中是相同的 " 字符,print( """ " \" """) => " ",请参阅 demo'\"' = '"',所以你对 .replace('\"', "'") 所做的只是将每个 " 替换为 '
  • @Ivan Ivković:错误是什么?如何将数据加载到 Pandas 中?根据 jsonlint.com,您的 JSON 数据是正确的。

标签: python json regex parsing double-quotes


【解决方案1】:

问题是你在不应该的时候转义了这些 \ 字符。通过在 """

前添加 r 来使用原始字符串
import json
text = r"""[{
   "article_id": 35449,
   "site_id": 153,
   "domain": "https:\/\/ezt.hq",
   "code": "wta-jurrda-pe-cetlu",
   "uri": "https:\/\/ezl.hr\/s0349\/wla-balu\/",
   "content_type": {
       "id": 1,
       "name": "article"
   },
   "article_type": {
       "id": 1,
       "name": "article"
   },
   "created": "2019-07-25 23:58:20",
   "modified": "2019-07-25 23:59:19",
   "publish_date": "2019-07-25 23:58:00",
   "active": true,
   "author": "<a href=\"https:\/\/spr2.hr\" target=\"_blank\">Iari<\/a>"
}]"""
obj = json.loads(text)

如果您从 txt 文件中读取文本,请将 text = r"""...""" 替换为 text = open(file_name).read()

【讨论】:

  • 是的,更大的问题是使用代码中的字符串进行测试,而不是首先解析原始内容。尝试直接解析 JSON。谢谢!
猜你喜欢
  • 2015-01-17
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
  • 2019-06-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-27
  • 2011-05-11
相关资源
最近更新 更多