【发布时间】:2014-09-21 21:55:23
【问题描述】:
我目前正在使用 Ruby 中的 Markov chain text generator 应用程序,该应用程序接收文本主体(“语料库”),然后根据该文本生成新文本。我目前需要解决的问题是编写一个正则表达式,它将返回包含我指定的单词数的数组。我在这里要做的就是抓取一定数量的单词(由用户指定),但在整个字符串中多次。
离开我见过的另一个应用程序,我正在使用/(([.,?"();\-!':—^\w]+ ){#{depth}})/ 之类的东西,其中#{depth} 一次插入多少个单词。这应该一次抓取两个单词,同时允许一部分特殊字符,这就是让我感兴趣的部分。所以总的问题是:如何动态指定我想要的单词数(由空格分隔),同时还允许这些单词中包含一系列特殊字符?
这是我目前拥有的:
# Regex
@match_regex = /(([.,?"();\-!':—^\w]+ ){2})/
s = input.scan(@match_regex).to_a
puts s.inspect
# Input
Within weeks they planned a meeting. She sent him poetry along with her itinerary,
having worked in a business meeting to excuse the opportunity. He prepared flowers
and a banner of welcome on his hearth.
# Output - seems to be grabbing last word again for some reason
[["Within weeks ", "weeks "], ["they planned ", "planned "], ["a meeting. ", "meeting. "],
["She sent ", "sent "], ["him poetry ", "poetry "], ["along with ", "with "],
["her itinerary, ", "itinerary, "], ["having worked ", "worked "], ["in a ", "a "],
["business meeting ", "meeting "], ["to excuse ", "excuse "],
["the opportunity. ", "opportunity. "], ["He prepared ", "prepared "], ["flowers and ", "and "],
["a banner ", "banner "], ["of welcome ", "welcome "], ["on his ", "his "]]
# Desired output. I'm not picky if it has trailing spaces or not as I can always trim that
["Within weeks", "they planned", "a meeting.", "She sent", "him poetry", "along with",
"her itinerary," "having worked", "in a", "business meeting", "to excuse", "the opportunity.",
"He prepared", "flowers and", "a banner", "of welcome", "on his"]
任何帮助将不胜感激。谢谢!
【问题讨论】:
标签: ruby regex markov-chains