使用Ruby更改段落中的每个单词

时间:2011-02-07 21:34:35

标签: ruby algorithm paragraphs

所以我用Ruby编码,我有几句话:

The sky above the port was the color of television, tuned to a dead channel. "It's not like I'm using," Case heard someone say, as he shouldered his way through the crowd around the door of the Chat. "It's like my body's developed this massive drug deficiency." It was a Sprawl voice and a Sprawl joke. The Chatsubo was a bar for professional expatriates; you could drink there for a week and never hear two words in Japanese.

我需要修改段落中的每个单词而不改变结构。我最初的想法是只是拆分空白然后重新加入它,但问题是你也得到了标点符号。如果你分开以便得到这个词,那么很难重新加入,因为你不知道正确的标点符号。

有没有比传统的拆分,地图,加入组合更好的方法呢?或者也许只是一个好的分裂正则表达式,所以它很容易重新加入?

2 个答案:

答案 0 :(得分:3)

将gsub与块一起使用:

str = %q(The sky above the port was the color of television, tuned to a dead channel.
"It's not like I'm using," Case heard someone say, as he shouldered his way through the crowd
around the door of the Chat. "It's like my body's developed this massive drug deficiency."
It was a Sprawl voice and a Sprawl joke. The Chatsubo was a bar for professional expatriates;
you could drink there for a week and never hear two words in Japanese.)

puts str.gsub(/\w+/){|word| word.tr('aeiou','uoaei') }

结果:

Tho sky ubevo tho pert wus tho celer ef tolovasaen, tinod te u doud chunnol.
"It's net lako I'm isang," Cuso hourd semoeno suy, us ho sheildorod has wuy threigh tho crewd
ureind tho deer ef tho Chut. "It's lako my bedy's dovolepod thas mussavo drig dofacaoncy."
It wus u Spruwl veaco und u Spruwl jeko. Tho Chutsibe wus u bur fer prefossaenul oxputrautos;
yei ceild drank thoro fer u wook und novor hour twe werds an Jupunoso.

好吧,这个#tr方法可以在没有正则表达式的情况下工作,但是你明白了。

答案 1 :(得分:3)

我会将单词边界之间的单词与正则表达式匹配,以避免影响标点符号或空格,例如:

s = "This is a test, ok?  Yes, fine!"
s.gsub!(/\b(\w+)\b/) {|x| "_#{x}_"}
s = "_This_ _is_ _a_ _test_, _ok_?  _Yes_, _fine_!"
相关问题