我有一个json文件如下:
[
{
"contributors": null,
"coordinates": null,
"created_at": "Fri Aug 04 21:12:59 +0000 2017",
"entities": {
"hashtags": [
{
"indices": [
32,
39
],
"text": "\ubd80\uc0b0\ucd9c\uc7a5\uc548\ub9c8"
},
{
"indices": [
40,
48
],
"text": "\ubd80\uc0b0\ucd9c\uc7a5\ub9c8\uc0ac\uc9c0"
}
]
},
"text": "\uaedb"
"retweeted_status": {
"contributors": null,
"coordinates": null,
"created_at": "Fri Aug 04 20:30:06 +0000 2017",
"display_text_range": [
0,
0
],
"text": "hjhfbsdjsdbjsd"
},
"extended_tweet": {
"display_text_range": [
0,
137
],
"entities": {
"hashtags": [
{
"indices": [
62,
75
],
"text": "2ndAmendment"
},
{
"indices": [
91,
104
],
"text": "1stAmendment"
}
]
}
}
}
]
我编写了下面的python代码来计算整个json文件中text
属性的数量。
data = json.load(data_file)
for key, value in data1.items():
if key=="text":
cnt+=1
elif key=="retweeted_status":
for k,v in value.items():
if k=="text":
cnt+=1
elif key == "entities":
if key.keys()=="hashtags" :
for k1,v1 in key:
# Difficult to loop further
由于数据结构不保持不变,因此难以迭代。此外,我想访问text
属性的值并显示它。如果没有多个循环,有没有更简单的方法呢?
答案 0 :(得分:1)
使用正则表达式怎么样?:
import re
regex_chain = re.compile(r'(text)\": \"(.*)\"')
text_ocurrences=[]
with open('1.json') as file:
for line in file:
match = regex_chain.search(line)
if match:
text_ocurrences.append({ match.group(1) : match.group(2)})
print(text_ocurrences)
您将获得一个dicts列表,其中每个包含键,文本出现的值
[{'text': '\\ubd80\\uc0b0\\ucd9c\\uc7a5\\uc548\\ub9c8'}, {'text': '\\ubd80\\uc0b0\\ucd9c\\uc7a5\\ub9c8\\uc0ac\\uc9c0'}, {'text': '\\uaedb'}, {'text': 'hjhfbsdjsdbjsd'}, {'text': '2ndAmendment'}, {'text': '1stAmendment'}]
答案 1 :(得分:0)
我不确定使用正则表达式天真地解析JSON是多么安全,尤其是(text)\": \"(.*)\"
技术上可以匹配text": "abc", "text": "another"
,其中第1组为text
且第2组为{ {1}}。
使用python的标准abc", "text": "another
库解析JSON更安全,然后递归遍历该数据。
json