我想在Ruby中基于停用词列表将字符串拆分为较小的子字符串或短语。当我直接定义正则表达式模式时,split方法可以正常工作;但是,当我尝试在split方法内部评估定义模式时,它无法正常工作。
实际上,我想读取停用词的外部文件并将其用于拆分句子。因此,我希望能够从外部文件构建模式,而不是直接指定它。我还注意到,当我使用'pp'和'puts'时,行为非常不同,我不确定原因。我在Windows上使用Ruby 2.0和Notepad ++。
上面的最终数组是我想要的结果。然而,下面的代码无法实现:
实际上,我想读取停用词的外部文件并将其用于拆分句子。因此,我希望能够从外部文件构建模式,而不是直接指定它。我还注意到,当我使用'pp'和'puts'时,行为非常不同,我不确定原因。我在Windows上使用Ruby 2.0和Notepad ++。
require 'pp'
str = "The force be with you."
pp str.split(/(?:\bthe\b|\bwith\b)/i)
=> ["", " force be ", " you."]
pp str.split(/(?:\bthe\b|\bwith\b)/i).collect(&:strip).reject(&:empty?)
=> ["force be", "you."]
上面的最终数组是我想要的结果。然而,下面的代码无法实现:
require 'pp'
stop_array = ["the", "with"]
str = "The force be with you."
pattern = "(?:" + stop_array.map{|i| "\b#{i}\b" }.join("|") + ")"
puts pattern
=> (?thwit)
puts str.split(/#{pattern}/i)
=> The force be with you.
pp pattern
=> "(?:\bthe\b|\bwith\b)"
pp str.split(/#{pattern}/i)
=> ["The force be with you."]
更新:根据下面的评论,我修改了原来的脚本。我还创建了一个方法来拆分字符串。
require 'pp'
class String
def splitstop(stopwords=[])
stopwords_regex = /\b(?:#{ Regexp.union(*stopwords).source })\b/i
return split(stopwords_regex).collect(&:strip).reject(&:empty?)
end
end
stop_array = ["the", "with", "over"]
pp "The force be with you.".splitstop stop_array
=> ["force be", "you."]
pp "The quick brown fox jumps over the lazy dog.".splitstop stop_array
=> ["quick brown fox jumps", "lazy dog."]
/(?:\bthe\b|\bwith\b)/
最好写成/\b(?:the|with)\b/
。 - the Tin Man