【问题标题】:Python parsing file that has single and double quotes, as well as contractions具有单引号和双引号以及缩写的 Python 解析文件
【发布时间】:2018-08-01 13:56:53
【问题描述】:

我正在尝试解析一个文件,其中某些行可能包含单引号、双引号和缩写的组合。每个观察都包含一个字符串,如上所示。在尝试解析数据时,我在尝试解析评论时遇到了问题。例如:

\'text\' : \'This is the first time I've tried really "fancy food" at a...\' 

\'text\' : \'I' be happy to go back "next hollidy"\' 

【问题讨论】:

  • 你为什么不直接使用json 模块?
  • @kindall 我正在使用 json 模块....问题是我收到的“json”实际上不是 json,因为它的格式是 '{\'address_components\': [{\'long_name\ ': \'Fairhope\', \'short_name\': ... 我必须重新格式化才能让 json.loads 正常工作
  • 虽然上面的字符串好像是json
  • @mad_ 不验证为 JSON 因为它需要用双引号而不是单引号所以 'long_name' : 'Fairhope' 应该是 "long_name" : "Fairhope" 或者至少这是唯一的我让 pyton 将其读取为 json 的方式。
  • 那么 json 标签和标题一样具有误导性,因为您根本没有 JSON。但如果不是 JSON,则无法回答这个问题,因为除了您,甚至您自己都不知道您拥有什么。

标签: python json parsing text-mining


【解决方案1】:

使用简单的双重替换预处理您的字符串 - 首先转义所有引号,然后用引号替换所有转义的撇号 - 这将简单地反转转义,例如:

# we'll define it as an object to keep the validity
src = "{\\'text\\' : \\'This is the first time I've tried really \"fancy food\" at a...\\'}"
# The double escapes are just so we can type it properly in Python.
# It's still the same underneath:
# {\'text\' : \'This is the first time I've tried really "fancy food" at a...\'}

preprocessed = src.replace("\"", "\\\"").replace("\\'", "\"")
# Now it looks like:
# {"text" : "This is the first time I've tried really \"fancy food\" at a..."}

它现在是一个有效的 JSON(顺便说一下,还有一个 Python 字典),因此您可以继续解析它:

import json

parsed = json.loads(preprocessed)
# {'text': 'This is the first time I\'ve tried really "fancy food" at a...'}

或者:

import ast

parsed = ast.literal_eval(preprocessed)
# {'text': 'This is the first time I\'ve tried really "fancy food" at a...'}

更新

根据发布的行,您实际上有一个 7 元素元组的(有效)表示,其中包含字典的字符串表示作为其第三个元素,您根本不需要预处理字符串。您需要首先评估元组,然后使用另一个评估级别对内部 dict 进行后处理,即:

import ast

# lets first read the data from a 'input.txt' file so we don't have to manually escape it
with open("input.txt", "r") as f:
    data = f.read()

data = ast.literal_eval(data)  # first evaluate the main structure
data = data[:2] + (ast.literal_eval(data[2]), ) + data[3:]  # .. and then the inner dict

# this gives you `data` containing your 'serialized' tuple, i.e.:
print(data[4])  # 31.328237,-85.811893
# and you can access the children of the inner dict as well, i.e.:
print(data[2]["types"])  # ['restaurant', 'food', 'point_of_interest', 'establishment']
print(data[2]["opening_hours"]["weekday_text"][3])  # Thursday: 7:00 AM – 9:00 PM
# etc.

话虽如此,我建议追踪生成此类数据的人,并说服他们使用某种适当形式的序列化,即使是最基本的 JSON 也会比这更好。

【讨论】:

  • 感谢您的洞察力,但对我来说不太有效。一旦我尝试过,它会给我带来以前不存在的解析问题。对于这部分的即时信息:\'adr_address\': \'913 Rucker Blvd #34, Enter
  • @nbas - 你能发布你试图解析的实际字符串吗?你对它有什么期望?提取的部分应该可以通过上述例程修复,但可能有些部分不符合模式。
  • 我已经更新了我的原始问题,其中有一条给我带来了困难。它位于页面顶部。
猜你喜欢
  • 2015-08-05
  • 2018-09-05
  • 1970-01-01
  • 2019-12-26
  • 1970-01-01
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
  • 2017-11-18
相关资源
最近更新 更多