【发布时间】:2016-06-28 08:22:52
【问题描述】:
我在 ipython 工作;我有一个 Yaml 文件和一个与我的 Yaml 文件相对应的 [thomas] id 列表(thomas:文件的第三行)。下面只是文件的一个小sn-p。完整的文件可以在这里找到 (https://github.com/108michael/congress-legislators/blob/master/legislators-historical.yaml)
- id:
bioguide: C000858
thomas: '00246'
lis: S215
govtrack: 300029
opensecrets: N00002091
votesmart: 53288
icpsr: 14809
fec:
- S0ID00057
wikipedia: Larry Craig
house_history: 11530
name:
first: Larry
middle: E.
last: Craig
bio:
birthday: '1945-07-20'
gender: M
religion: Methodist
terms:
- type: rep
start: '1981-01-05'
end: '1983-01-03'
state: ID
district: 1
party: Republican
- type: rep
start: '1983-01-03'
end: '1985-01-03'
state: ID
district: 1
party: Republican
我想解析文件,对于列表中与 [thomas:] 中的 Id 对应的每个 id,我想检索以下内容:[fec]:(可能不止一个,我需要所有其中)[姓名:] [第一:] [中间:] [最后:]; [简历:] [生日:]; [terms:](可能不止一个term,我需要所有terms)[type:] [start:] [state:] [party:]。最后,也可能存在 fec 数据不可用的情况。
1) 我应该如何存储数据?我对 Python(我的第一种编程语言)还比较陌生,不知道如何存储数据。直观地说,我会说字典;然而,最重要的是易于访问和数据检索。以前,我将类似的嵌套数据存储为 csv。这种方法似乎有点笨重。如果我可以(从我拥有的 thomas ids)列出字典(我正在检索的数据),这似乎是理想的。
2) 我不确定如何设置 for/while 语句,以便仅检索与我的 thomas id 列表对应的数据。
我开始编写我期望的将信息写入 CSV 的代码:
import pandas as pd
import yaml
import glob
import CSV
df = pd.concat((pd.read_csv(f, names=['date','bill_id','sponsor_id']) for f in glob.glob('/home/jayaramdas/anaconda3/df/s11?_s_b')))
outputfile = open('sponsor_details', 'W', newline='')
outputwriter = csv.writer(outputfile)
df = df.drop_duplicates('sponsor_id')
sponsor_list = df['sponsor_id'].tolist()
with open('legislators-historical.yaml', 'r') as f:
data = yaml.load(f)
for sponsor in sponsor_list:
where sponsor == data[0]['thomas']:
x = data[0]['thomas']
a = data[0]['name']['first']
b = data[0]['name']['middle']
c = data[0]['name']['last']
d = data[0]['bio']['gender']
e = data[0]['bio']['religion']
for fec in data[0]['id']:
c = fec.get('fec')
for terms in data[0]['id']:
t = terms.get('type')
s = terms.get('start')
state = terms.get('state')
p = terms.get('party')
outputwriter.writerow([x, a, b, c, d, e, c, t, s, state, p])
outputfile.flush()
我收到以下错误:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-48-057d25de7e11> in <module>()
15
16 for sponsor in sponsor_list:
---> 17 if sponsor == data[0]['thomas']:
18 x = data[0]['thomas']
19 a = data[0]['name']['first']
KeyError: 'thomas'
【问题讨论】:
-
也许可以帮助将
for sponsor in sponsor_list as f:更改为for sponsor in sponsor_list: -
我刚刚尝试了您的建议和问题。我仍然收到以下错误:
File "<ipython-input-39-2535ffac2b4d>", line 17 where sponsor == data[0][thomas]: ^ SyntaxError: invalid syntax -
是的,看起来也很糟糕。但我从不使用
yaml。也许一种方法是将yaml转换为json,然后使用pd.read_json创建DataFrame。 -
好的!我会调查的。
-
您可以在某处发布或上传具有 多个 id 的更大 yaml 文件吗?