ruby - 如何使用要在倒排索引中使用的正则表达式匹配 Ruby 中的多行字符串?

标签 ruby regex inverted-index

赋值说明:http://pastebin.com/pxJS4gfR

目标:获取文档集合并生成其倒排索引。

我的计划

  1. 从集合文件中抓取相关字符串
  2. 对它们进行标记并将它们放入哈希中以备后用。

我正在使用以下正则表达式 \.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/

相关文章:

javascript - 使用正则表达式计算字符串中引号的数量

regex - Lisp 正则表达式匹配带有或不带有常量类型标识符( 3.2 或 3.2f )的数字

regex - Vim 正则表达式匹配 unicode 字符作为非单词

MySQL:搜索文件内容的最佳方式(全文搜索)

solr - 在 HBase 之上的 solr 中创建索引

php - 在倒排索引算法中避免竞争条件的技术

ruby:使用正则表达式将 http://anything 替换为 <a href ="http://anything">http://anything</a>

ruby-on-rails - 取消ajax请求导致rails抛出异常

Ruby 从字符串数组中提取子字符串

ruby-on-rails - 加权嵌套集