使用python访问yaml文件中的字段
所以,我找到了其他堆栈溢出代码来获取字段,这就是我的典型示例使用python访问yaml文件中的字段,python,file,yaml,Python,File,Yaml,所以,我找到了其他堆栈溢出代码来获取字段,这就是我的典型示例 - id: bioguide: B000226 govtrack: 401222 icpsr: 507 name: first: Richard last: Bassett bio: birthday: '1745-04-02' gender: M terms: - type: sen start: '1789-03-04' end: '179
- id:
bioguide: B000226
govtrack: 401222
icpsr: 507
name:
first: Richard
last: Bassett
bio:
birthday: '1745-04-02'
gender: M
terms:
- type: sen
start: '1789-03-04'
end: '1793-03-02'
state: DE
class: 2
party: Anti-Administration
我有大约12000个我想解析的,一旦我理解了其中一个,就让它运行吧。现在我只是想做一些简单的事情,比如在文件中找到一个人的名字,所以我尝试了这个
for filename in os.listdir(currentPath):
print filename
if(filename.endswith(".yaml")):
with open(os.path.join(currentPath, filename)) as myFile:
results = yaml.load(myFile)
try:
print results["name"]["first"]
except:
print "Problem"
如果我不尝试捕捉异常,我会遇到这个问题,我不知道为什么,因为yaml文件不是像json文件那样的字典吗?似乎它把我理解为一个列表
print results["name"]["first"]
TypeError: list indices must be integers, not str
我遗漏了一些基本的东西,我唯一的障碍就是从yaml获取数据,如果有一些见解,我将不胜感激
编辑:
当我打印12000的其中一个文件时,它采用这种格式
[{'bio': {'gender': 'M', 'birthday': '1914-06-09'}, 'terms': [{'start': '1963-01-09', 'state': 'CA', 'end': '1964-10-03', 'district': 34, 'party': 'Democrat', 'type': 'rep'}, {'start': '1965-01-04', 'state': 'CA', 'end': '1966-10-22', 'district': 34, 'party': 'Democrat', 'type': 'rep'}, {'start': '1967-01-10', 'state': 'CA', 'end': '1968-10-14', 'district': 34, 'party': 'Democrat', 'type': 'rep'}, {'start': '1969-01-03', 'state': 'CA', 'end': '1971-01-02', 'district': 34, 'party': 'Democrat', 'type': 'rep'}, {'start': '1971-01-21', 'state': 'CA', 'end': '1972-10-18', 'district': 34, 'party': 'Democrat', 'type': 'rep'}, {'start': '1973-01-03', 'state': 'CA', 'end': '1974-12-20', 'district': 34, 'party': 'Democrat', 'type': 'rep'}], 'id': {'bioguide': 'H000164', 'icpsr': 10594, 'house_history': 14486, 'wikipedia': 'Richard T. Hanna', 'thomas': '00494', 'govtrack': 405046}, 'name': {'middle': 'Thomas', 'last': 'Hanna', 'first': 'Richard'}}]
如果您能帮助我,并告诉我如何访问一些内容,例如名称、开始和结束日期等,这将非常有帮助。这样行吗
try:
print results[0]['name']['first']
except:
print 'Problem'
您可以尝试将
“r”
传递给打开
命令,以明确指示它以读取权限打开。另外,如果你打印yaml.dump(myFile)
,你会得到什么?为什么不打印结果,看看发生了什么?当我打印一个结果时,我得到了这个[{bio':{gender':'M','birth':'1914-06-09','terms':[{'start':'1963-01-09','state':'CA','end':'1964-10-03','district':34','party':'democratic','type':'rep'},…无法全部显示,但我认为这显示了它的格式。将完整内容添加到我的原始帖子中。您能否正确缩进示例.yaml文件,以便我可以尝试它?这确实有效,第一个数字元素表示什么,顺序1,2…是什么意思?我看到了它们之间的关系以及从这里开始的方向。谢谢救命啊!