我已经从文本文件中创建了一个英文单词及其值的哈希表,方法是将每行中的第一个单词解析为要定义的单词,并使用以下代码解释所有单词,但第一个单词作为定义:< / p>
words = Hash.new
File.open("path/dictionary.txt") do|file|
file.each do |line|
n = line.split.size
definition = line.strip[/(?<=\s).*/]
words[line.strip.split[0...1]] = definition
end
end
但是,当我尝试使用如下代码打印值时:
p words["Definition"]
打印&#39; nil&#39;。我仍然可以使用&#39; p&#39;来打印整个哈希表。所以我不明白有任何想法吗?感谢
编辑:这是dictionary.txt的开头,让您了解我在做什么:
A- prefix (also an- before a vowel sound) not, without (amoral). [greek]
Aa abbr. 1 automobile association. 2 alcoholics anonymous. 3 anti-aircraft.
Aardvark n. Mammal with a tubular snout and a long tongue, feeding on termites. [afrikaans]
Ab- prefix off, away, from (abduct). [latin]
Aback adv. take aback surprise, disconcert. [old english: related to *a2]
Abacus n. (pl. -cuses) 1 frame with wires along which beads are slid for calculating. 2 archit. Flat slab on top of a capital. [latin from greek from hebrew]
Abaft naut. —adv. In the stern half of a ship. —prep. Nearer the stern than. [from *a2, -baft: see *aft]
Abandon —v. 1 give up. 2 forsake, desert. 3 (often foll. By to; often refl.) Yield to a passion, another's control, etc. —n. Freedom from inhibitions. abandonment n. [french: related to *ad-, *ban]
Abandoned adj. 1 deserted, forsaken. 2 unrestrained, profligate.
Abase v. (-sing) (also refl.) Humiliate, degrade. abasement n. [french: related to *ad-, *base2]
Abashed predic. Adj. Embarrassed, disconcerted. [french es- *ex-1, baïr astound]
Abate v. (-ting) make or become less strong etc.; diminish. abatement n. [french abatre from latin batt(u)o beat]
Abattoir n. Slaughterhouse. [french abatre fell, as *abate]
Abbacy n. (pl. -ies) office or jurisdiction of an abbot or abbess. [latin: related to *abbot]
Abbé n. (in france) abbot or priest. [french from latin: related to *abbot]
Abbess n. Head of a community of nuns.
Abbey n. (pl. -s) 1 building(s) occupied by a community of monks or nuns. 2 the community itself. 3 building that was once an abbey.
答案 0 :(得分:1)
由于你没有发布文字,很难说你想要什么,但我想这就是你想要的:
words = {}
File.foreach("path/dictionary.txt") do |line|
words.store(*line.strip.split(/\s+/, 2))
end
如果文字中有空行,
words = {}
File.foreach("path/dictionary.txt") do |line|
words.store(*line.strip.split(/\s+/, 2)) if line =~ /\S/
end
答案 1 :(得分:1)
看起来哈希中的键是包含一个元素的数组。
更改为
words[line.strip.split[0...1][0]]=definition