我使用 Scrapy 将一些 JSON 数据抓取到一个名为“wotd-page-one.json”的文件中。JSON 数据包含一些西班牙语单词,重音字母被转换为 Unicode。我想加载这些数据并在同一目录中使用 python 脚本使其变得可用。我正在尝试将此数据加载到列表中以单独处理每个 JSON 键和值。但是,我很难做到这一点,因为我没有大量使用 Unicode 和 JSON 的经验。任何人都可以帮我找到一种方法来通过 Python 列表访问这些数据。理想情况下,我想使它像 data[2] == "DEF" data[3] == "string with any unicode characters convert to latin-1" and data[4] == "SENTENCE" data[5] ==“将任何 unicode 字符转换为 latin-1 的字符串”
Python file:
data=[]
with open('wotd-page-one.json', encoding='utf-8') as f:
for line in f:
line = line.replace('\n', '')
data.append(line)
print(data)
JSON file:
[
{"TRANSLATION": "I don't like how that guy's whistling; it gives me the creeps.", "WORD": "silbar", "DEF": "to whistle", "SENTENCE": "No me gusta c\u00f3mo silba ese se\u00f1or; me da escalofr\u00edos."},
{"TRANSLATION": "\"Is somebody there?\" asked the boy in a startled voice.", "WORD": "sobresaltado", "DEF": "startled", "SENTENCE": "\"\u00bfHay alguien aqu\u00ed?\" pregunt\u00f3 el ni\u00f1o con voz sobresaltada."},
{"TRANSLATION": "Carla made a face at me when I asked her if she was scared.", "WORD": "la mueca", "DEF": "face", "SENTENCE": "Carla me hizo una mueca cuando le pregunt\u00e9 si ten\u00eda miedo."},
{"TRANSLATION": "The teacher tapped the board with the chalk.", "WORD": "golpetear", "DEF": "to tap", "SENTENCE": "El maestro golpete\u00f3 el pizarr\u00f3n con la tiza."}
]
Output:
['[',
'{"TRANSLATION": "I don\'t like how that guy\'s whistling; it gives me the creeps.", "WORD": "silbar", "DEF": "to whistle", "SENTENCE": "No me gusta c\\u00f3mo silba ese se\\u00f1or; me da escalofr\\u00edos."},', '
{"TRANSLATION": "\\"Is somebody there?\\" asked the boy in a startled voice.", "WORD": "sobresaltado", "DEF": "startled", "SENTENCE": "\\"\\u00bfHay alguien aqu\\u00ed?\\" pregunt\\u00f3 el ni\\u00f1o con voz sobresaltada."},', '
{"TRANSLATION": "Carla made a face at me when I asked her if she was scared.", "WORD": "la mueca", "DEF": "face", "SENTENCE": "Carla me hizo una mueca cuando le pregunt\\u00e9 si ten\\u00eda miedo."},', '
{"TRANSLATION": "The teacher tapped the board with the chalk.", "WORD": "golpetear", "DEF": "to tap", "SENTENCE": "El maestro golpete\\u00f3 el pizarr\\u00f3n con la tiza."}', ']']
使用 JSON 文件,您可以通过一次操作加载它。它将变成一个 Python 结构......在这种情况下,是一个字典列表。例如:
import json
with open('wotd-page-one.json') as f:
data = json.load(f)
for d in data:
print(d['SENTENCE'])
输出:
No me gusta cómo silba ese señor; me da escalofríos.
"¿Hay alguien aquí?" preguntó el niño con voz sobresaltada.
Carla me hizo una mueca cuando le pregunté si tenía miedo.
El maestro golpeteó el pizarrón con la tiza.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句