【发布时间】:2019-01-18 15:51:25
【问题描述】:
我正在使用 python 解析一个包含 url 数据的 json 文件,以尝试构建一个 url 信誉分类器。 json 文件中有大约 2,000 个条目,但并非所有条目都包含所有字段。一个典型的条目如下所示:
[
{
"host_len" : 12,
"fragment" : null,
"url_len" : 84,
"default_port" : 80,
"domain_age_days" : "5621",
"tld" : "com",
"num_domain_tokens" : 3,
"ips" : [
{
"geo" : "CN",
"ip" : "115.236.98.124",
"type" : "A"
}
],
"malicious_url" : 0,
"url" : "http://www.oppo.com/?utm_source=WeiBo&utm_medium=OPPO&utm_campaign=DailyFlow",
"alexa_rank" : "25523",
"query" : "utm_source=WeiBo&utm_medium=OPPO&utm_campaign=DailyFlow",
"file_extension" : null,
"registered_domain" : "oppo.com",
"scheme" : "http",
"path" : "/",
"path_len" : 1,
"port" : 80,
"host" : "www.oppo.com",
"domain_tokens" : [
"www",
"oppo",
"com"
],
"mxhosts" : [
{
"mxhost" : "mail1.oppo.com",
"ips" : [
{
"geo" : "CN",
"ip" : "121.12.164.123",
"type" : "A"
}
]
}
],
"path_tokens" : [
""
],
"num_path_tokens" : 1
}
]
我正在尝试访问存储在“ips”和“mxhosts”字段中的数据以比较“geo”位置。尝试访问我正在使用的第一个“ips”字段:
corpus = open(file)
urldata = json.load(corpus, encoding="latin1")
for record in urldata:
print record["ips"][0]["geo"]
但正如我提到的,并非所有 json 条目都具有所有字段。 “ips”总是存在,但有时它是“null”,“geo”也是如此。我正在尝试在使用以下方式访问数据之前检查数据:
if(record["ips"] is not None and record["ips"][0]["geo"] is not None):
但我这是一个错误:
if(record["ips"] is not None and record["ips"][0]["geo"] is not None):
TypeError: string indices must be integers
当我尝试使用这个来检查它时:
if("ips" in record):
我收到此错误消息:
print record["ips"][0]["geo"]
TypeError: 'NoneType' object has no attribute '__getitem__'
所以我不确定如何在访问之前检查我尝试访问的记录是否存在,或者我什至是否以最正确的方式访问。谢谢。
【问题讨论】:
-
据我了解,上面的数据是urldata。如果是这种情况,而不是 record["ips"][0]["geo"] 做 record["ips"]["geo"]。这应该有效。
-
感谢您的反馈。这样做会给我一个错误:
TypeError: list indices must be integers, not str然而。