2011-02-07 10 views
1

と段落内のすべての単語:変更だから私は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

Oh awesomeと再結合できるからです。完全にドキュメントでgsubが見られませんでした。私は盲目でなければならない。また、%qはかなり素晴らしいです。ありがとう! – icco

3

私は句読点や空白への影響を回避するために正規表現と単語の境界の間の単語、例えば一致します

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

これは上記の答えと非常に似ていますが、正規表現は少し異なります。なぜ '/ \ w + /'だけで '/ \ b(\ w +)\ b /'を選んだのですか? – icco

+0

+1私よりも言葉を変えた方がいい。しかし、Iccoが言ったように、なぜ複雑な正規表現ですか? – steenslag

関連する問題