【发布时间】:2019-05-22 09:52:24
【问题描述】:
我正在尝试解析文件中的一些数据并将其存储到哈希映射中,而不是使用正则表达式而是字符串比较,并且我遇到了一些我尝试修复但没有解决问题的错误。
文件的结构如下:
"key" + "double colon" + "value"
在每一行。这种结构沿文件重复,每个数据都有一个 ID 键,几乎所有数据都至少有一个“is_a”键,还可能有“is_obsolete”和“replaced_by”键。
我试图像这样解析它:
def get_hpo_data(hpofile="hp.obo")
hpo_data = Hash.new() #Hash map where i want to store all IDs
File.readlines(hpofile).each do |line|
if line.start_with? "id:" #if line is an ID
hpo_id = line[4..13] #Store ID value
hpo_data[hpo_id] = Hash.new() #Setting up hash map for that ID
hpo_data[hpo_id]["parents"] = Array.new()
elsif line.start_with? "is_obsolete:" #If the ID is obsolete
hpo_data[hpo_id]["is_obsolete"] = true #store value in the hash
elsif line.start_with? "replaced_by:" #If the ID is obsolete
hpo_data[hpo_id]["replaced_by"] = line[13..22]
#Store the ID term it was replaced by
elsif line.start_with? "is_a:" #If the ID has a parent ID
hpo_data[hpo_id]["parents"].push(line[6..15])
#Store the parent(s) in the array initialized before
end
end
return hpo_data
end
我期望创建的结构是一个全局哈希,其中每个 ID 也是一个带有不同数据的哈希(一个字符串数据、一个布尔值和一个可变长度的数组,具体取决于该 ID 的父 ID 的数量)术语,但我收到以下错误:
table_combination.rb:224:in `block in get_hpo_data': undefined method `[]=' for nil:NilClass (NoMethodError)
这次错误指向replaced_byelsif 语句,但我也可以通过任何其他elsif 语句得到它,因此代码无法解析“is_obsolete”、“replaced_by”和“is_a” “ 特性。如果我尝试删除这些语句,代码会成功创建全局散列,并将每个 ID 项作为散列。
我也尝试为每个哈希值提供默认值,但这并不能解决问题。我什至遇到了一个以前从未见过的新错误:
table_combination.rb:233:in '[]': no implicit conversion of String into Integer (TypeError)
在这一行:
hpo_data[hpo_id]["parents"].push(line[6..15])
以下是两个术语的文件外观示例,显示了我要处理的不同键:
[Term]
id: HP:0002578
name: Gastroparesis
def: "Decreased strength of the muscle layer of stomach, which leads to a decreased ability to empty the contents of the stomach despite the absence of obstruction." [HPO:probinson]
subset: hposlim_core
synonym: "Delayed gastric emptying" EXACT layperson [ORCID:0000-0001-5208-3432]
xref: MSH:D018589
xref: SNOMEDCT_US:196753007
xref: SNOMEDCT_US:235675006
xref: UMLS:C0152020
is_a: HP:0002577 ! Abnormality of the stomach
is_a: HP:0011804 ! Abnormal muscle physiology
[Term]
id: HP:0002564
name: obsolete Malformation of the heart and great vessels
is_obsolete: true
replaced_by: HP:0030680
【问题讨论】:
-
欢迎来到 SO!我们需要可运行并演示问题的示例代码。您要求我们编写一个测试工具来证明/反驳您的代码并对其进行调试,但这是您的工作。 How to Ask 将帮助您了解我们的需求。
-
@theTinMan 这个问题并不完美,但它仍然可以很好地显示输入是什么,问题是什么以及 OP 尝试了什么。