我正在构建一个下载句子并解析它们以进行文字游戏的应用程序。我事先并不知道文本中包含的标点符号。
我希望能够将句子分开,检查它们的词性标记,如果找到了正确的标记,请将其替换为" "
,然后按顺序重新加入它们。
text = "some string, with punctuation- for example: things I don't know about, that may or may not have whitespaces and random characters % !!"
如何将其拆分为数组,以便我可以将解析器传递给每个单词,然后按顺序重新加入 ,同时考虑到string.split(//)
似乎需要知道什么标点符号我在找?
答案 0 :(得分:6)
split
非常有用。在您的情况下,您可以更轻松地描述要提取的部分而不是分隔符,在这种情况下scan
更适合。使用split
是错误的决定。你应该scan
。
text.scan(/[\w']+/)
# => ["some", "string", "with", "punctuation", "for", "example", "things", "I", "don't", "know", "about", "that", "may", "or", "may", "not", "have", "whitespaces", "and", "random", "characters"]
如果您想要替换匹配项,则更有理由不使用split
。在这种情况下,您应该使用gsub
。
text.gsub(/[\w']+/) do |word|
if word.is_of_certain_part_of_speech?
"___" # Replace it with `"___"`.
else
word # Put back the original word.
end
end