赋值说明:http://pastebin.com/pxJS4gfR
目标:获取文档集合并生成其倒排索引。
我的计划
- 从集合文件中抓取相关字符串
- 对它们进行标记并将它们放入哈希中以备后用。
我正在使用以下正则表达式 \.I(.*?)\.B\m
从集合文件中获取所需的文本,如下所示:http://rubular.com/r/mOpfuvRT12
编辑:我使用了mudasobwa
的建议
content = File.read('test.txt')
# deal with content
content.scan(/\.T(.*?)\.B/m) { |mtch|
puts mtch
}
这抓取了我需要的必要文本,但是我需要将抓取的文本放入哈希中以备后用,我不确定如何使用 String.scan/regex/
因为它返回数组的数组。
我基本上是在尝试复制这个例子:
puts "Enter something: "
text = gets.chomp
words = text.split(" ")
frequencies = Hash.new(0)
words.each do |word|
frequencies[word] += 1
end
frequencies = frequencies.sort_by { |k, v| v }
frequencies.reverse!
frequencies.each do |word, freq|
puts word + " " + freq.to_s
end
最佳答案
您正在尝试逐行读取文件。在这种情况下,/m
多行修饰符没有意义。您将读取整个文件,然后根据需要对其进行解析:
content = File.read('test.txt')
content.scan(/\.T(.*?)\.B/m) { |mtch|
puts mtch
}
UPD
要像示例中那样将扫描结果散列,您需要数组的 flatten
方法:
content = File.read('test.txt')
# flatten the array ⇓⇓⇓⇓⇓⇓⇓
words = content.scan(/\.T(.*?)\.B/m).flatten
words.each …
或在 scan
方法中阻止:
content = File.read('test.txt')
freqs = {}
content.scan(/\.T(.*?)\.B/m) { |mtch|
(freqs[mtch] ||= 0) += 1
}
…
UPD2 将生成的句子数组拆分
为单词数组:
arr = ["Preliminary Report International", "Fingers or Fists"]
arr.map {|e| e.split(' ')}.flatten.map(&:downcase)
# ⇒ ["preliminary", "report", "international", "fingers", "or", "fists"]
这里首先 map
迭代数组元素并将它们转换为拆分单词的数组,flatten
从产生的数组数组生成普通数组,最后,downcase
在这里是因为您在示例中请求了小写的单词。
希望对您有所帮助。
关于ruby - 如何使用要在倒排索引中使用的正则表达式匹配 Ruby 中的多行字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19148795/