1. 准备数据
在此习题集中,你将处理另一种类型的 infobox 数据,审核、清理数据,并得出一种数据模型,将数据插入 MongoDB,然后对数据库运行一些查询。数据集中包含关于蛛形纲动物的数据。
对于这道练习,你的任务是解析文件,仅处理 FIELDS 字典中作为键的字段,并返回清理后的值字典列表。
你应该完成以下几个步骤:
- 根据 FIELDS 字典中的映射更改字典的键
- 删掉“rdf-schema#label”中的小括号里的多余说明,例如“(spider)”
- 如果“name”为“NULL”,或包含非字母数字字符,将其设为和“label”相同的值。
- 如果字段的值为“NULL”,将其转换为“None”
- 如果“synonym”中存在值,应将其转换为数组(列表),方法是删掉“{}”字符,并根* 据“|” 拆分字符串。剩下的清理方式将由你自行决定,例如删除前缀“*”等。如果存在单数同义词,值应该依然是列表格式。
- 删掉所有字段前后的空格(如果有的话)
输出结构应该如下所示:
[ { 'label': 'Argiope',
'uri': 'http://dbpedia.org/resource/Argiope_(spider)',
'description': 'The genus Argiope includes rather large and spectacular spiders that often ...',
'name': 'Argiope',
'synonym': ["One", "Two"],
'classification': {
'family': 'Orb-weaver spider',
'class': 'Arachnid',
'phylum': 'Arthropod',
'order': 'Spider',
'kingdom': 'Animal',
'genus': None
}
},
{ 'label': ... , }, ...
]
import codecs
import csv
import json
import pprint
import re
DATAFILE = 'arachnid.csv'
FIELDS ={'rdf-schema#label': 'label',
'URI': 'uri',
'rdf-schema#comment': 'description',
'synonym': 'synonym',
'name': 'name',
'family_label': 'family',
'class_label': 'class',
'phylum_label': 'phylum',
'order_label': 'order',
'kingdom_label': 'kingdom',
'genus_label': 'genus'}
def process_file(filename, fields):
process_fields = fields.keys()
data = []
with open(filename, "r") as f:
reader = csv.DictReader(f)
for i in range(3):
l = reader.next()
for line in reader:
# YOUR CODE HERE
set = {}
set['classification'] = {}
for i in process_fields:
new_field = fields[i]
temp_value = line[i].strip()
if temp_value == 'NULL':
temp_value = None
if i=='rdf-schema#label':
temp_value = re.sub(r'\(.*\)',' ',temp_value).strip()
if i=='name' and line[i] =='NULL':
temp_value = line['rdf-schema#label'].strip()
if i=='synonym' and temp_value:
temp_value = parse_array(line[i])
if new_field in ["kingdom", "family", "order", "phylum", "genus", "class"]:
set['classification'][new_field] = temp_value
continue
set[new_field] = temp_value
data.append(set)
pass
return data
def parse_array(v):
if (v[0] == "{") and (v[-1] == "}"):
v = v.lstrip("{")
v = v.rstrip("}")
v_array = v.split("|")
v_array = [i.strip() for i in v_array]
return v_array
return [v]
2. 向 MongoDB 插入数据
Complete the insert_data function to insert the data into MongoDB.
import json
def insert_data(data, db):
db.arachnid.insert(data)
# Your code here. Insert the data into a collection 'arachnid'
pass
if __name__ == "__main__":
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")
db = client.examples
with open('arachnid.json') as f:
data = json.loads(f.read())
insert_data(data, db)
print db.arachnid.find_one()