Ruby扫描以匹配多个单词

Ruby扫描以匹配多个单词,ruby,regex,Ruby,Regex,我有一个代码,可以解析文件夹中的文本文件,并在某个搜索词周围保存文本 但是,我在编辑代码时遇到了问题,无法同时处理多个单词。我不想循环整个代码,因为我希望为每个文本文件分组结果,而不是为每个搜索词分组结果 使用所有文档.scan((word1 | word2 | word3)”)或类似的正则表达式变体似乎不起作用 #helper def indices text, index, word padding = 20 bottom_i = in

我有一个代码,可以解析文件夹中的文本文件,并在某个搜索词周围保存文本

但是,我在编辑代码时遇到了问题,无法同时处理多个单词。我不想循环整个代码,因为我希望为每个文本文件分组结果,而不是为每个搜索词分组结果

使用
所有文档.scan((word1 | word2 | word3)”)
或类似的正则表达式变体似乎不起作用

    #helper
        def indices text, index, word
        padding = 20
        bottom_i = index - padding < 0 ? 0 : index - padding
        top_i = index + word.length + padding > text.length ? text.length : index +         word.length + padding
        return bottom_i, top_i
    end

    #script
    base_text = File.open("base.txt", 'w')
    Dir::mkdir("summaries") unless File.exists?("summaries")
    Dir.chdir("summaries")

    Dir.glob("*.txt").each do |textfile|
        whole_file = File.open(textfile, 'r').read
        puts "Currently summarizing " + textfile + "..."
        curr_i = 0
        str = nil
        whole_file.scan(/trail/).each do |match|
          if i_match = whole_file.index(match, curr_i)
            top_bottom = indices(whole_file, i_match, match)
            base_text.puts(whole_file[top_bottom[0]..top_bottom[1]] + " : " +         File.path(textfile))
            curr_i += i_match                     
          end
        end
        puts "Done summarizing " + textfile + "."
    end
    base_text.close
#助手
def索引文本、索引、单词
填充=20
底部=索引-填充<0?0:索引填充
top_i=索引+单词长度+填充>文本长度?text.length:index+word.length+padding
返回底部,顶部
结束
#剧本
base_text=File.open(“base.txt”,“w”)
目录::mkdir(“摘要”),除非File.exists?(“摘要”)
chdir总监(“摘要”)
Dir.glob(“*.txt”)。每个do |文本文件|
整个文件=文件。打开(文本文件,'r')。读取
放入“当前汇总”+文本文件+“…”
电流i=0
str=nil
整个文件。扫描(/trail/)。每个文件都不匹配|
如果i\u match=整个文件.index(匹配,curr\u i)
top\u bottom=索引(整个文件、i\u匹配、匹配)
base_text.put(整个_文件[top_bottom[0]…top_bottom[1]+”:“+file.path(textfile))
电流i+=电流匹配
结束
结束
将“完成汇总”+文本文件+”
结束
base_text.close
有什么想法吗?

你可以用它。这正是你想要的

在您的代码中,它将成为

...
whole_file.scan(Regexp.union(/trail/, /word1/, /word2/, /word3/)).each do |match|
...

我认为您最好
扫描
任何单词(例如通过
/[\w']+/
),并在
扫描
的块中,检查
$&
是否匹配任何特定单词。如果
scan
碰巧匹配了一个你不感兴趣的单词,那么就没有什么错;忽略它。

您可以使用
Regexp.union
,但这只是生成子字符串匹配。如果你想匹配完整的单词,你需要做更多的工作。我会使用:

/\b(?:#{ Regexp.union(%w[trail word1 word2 word3]).source })\b/
=> /\b(?:trail|word1|word2|word3)\b/
结果模式将定位整个单词,忽略任何子字符串:

foo = /\b(?:#{ Regexp.union(%w[trail word1 word2 word3]).source })\b/
# /\b(?:trail|word1|word2|word3)\b/

words = %w[trail word1 word2 word3]
words.join(' ').scan(foo)
# [
#     [0] "trail",
#     [1] "word1",
#     [2] "word2",
#     [3] "word3"
# ]

words.join.scan(foo)
# []

'trail word1word2 word3'.scan(foo)
# [
#     [0] "trail",
#     [1] "word3"
# ]

完美的它起作用了。谢谢