2013-03-28 42 views
6

我正在尝试在html载入文本的两个主体之间产生一个人类可读的类似wiki的区别。我使用的是diff-lcs,第一步是将字符串(字符数组)分成一组句子,但保留标点符号。将文本正文拆分为句子,但保留标点符号?

"I am a lion. Hear me roar! Where is my cub? Never mind, found him.".magic_split(/[.?!]/) 
# => "I am a lion." "Hear me roar!" "Where is my cub?" "Never mind, found him." 

这应该做的伎俩

"I am a lion. Hear me roar! Where is my cub? Never mind, found him.".gsub(/[.?!]/, '\1|').split('|') 

除了GSUB似乎有麻烦的插入字符.?!。相反,它返回这

"I am a lion| Hear me roar| Where is my cub| Never mind, found him|" 

什么是最简单的方法来做一个非破坏性拆分?正如它保留了它分裂的角色。

回答

3

我认为这应该是\0

>> string = "I am a lion. Hear me roar! Where is my cub? Never mind, found him." 
>> string.gsub(/[.?!]/, '\0|') 
    # "I am a lion.| Hear me roar!| Where is my cub?| Never mind, found him.|" 
11

scan应该做的伎俩(抛出strip在那里摆脱尾随空格)。

s = "I am a lion. Hear me roar! Where is my cub? Never mind, found him." 
s.scan(/[^\.!?]+[\.!?]/).map(&:strip) # => ["I am a lion.", "Hear me roar!", "Where is my cub?", "Never mind, found him."] 
+0

你会如何修改这个,如果你想追上一个句子结尾的“...”像“我是一头狮子。听我怒吼!我的幼崽在哪?不要紧,发现他......“ – michaelsking1993

+0

我编辑过它,如下所示:'text.scan(/[^\.!?]+[\.!?]+/)map(& :strip)“唯一的问题就是没有一段时间地抓住最后一句话:”我是狮子,听到我咆哮!你叫什么名字?不要评价我“,错过了最后的”不要判断我“ – michaelsking1993

+1

Working solution:'text.scan(/[^\.!?]+[\.!?]+ | [^ \。!?] +。\ z /)。map(&:strip)'(there可能是更优雅的方式,但这是工作)。输入:“我是狮子......听到我咆哮!!你叫什么名字?不要评价我” - >输出:“[”我是狮子......“”听到我咆哮!!“ ,“你叫什么名字?”,“不要判断我”)“ – michaelsking1993

相关问题