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.

そして、構造を変更せずに段落内のすべての単語を変更する必要があります。私の当初のアイデアは、空白を分割してから再結合することでしたが、それに関する問題は、句読点も取得することです。単語がわかるように分割すると、適切な句読点がわからないため、再結合するのが困難になります。

従来の分割、マップ、結合コンボよりもこれを行うためのより良い方法はありますか?または、再参加するのが簡単な、ちょうど良い分割正規表現でしょうか?

4

2 に答える 2

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メソッドは正規表現なしで機能しますが、あなたはその考えを理解します。

于 2011-02-07T21:48:52.900 に答える
3

句読点や空白に影響を与えないように、単語の境界と正規表現の間の単語を一致させます。例:

s = "This is a test, ok?  Yes, fine!"
s.gsub!(/\b(\w+)\b/) {|x| "_#{x}_"}
s = "_This_ _is_ _a_ _test_, _ok_?  _Yes_, _fine_!"
于 2011-02-07T21:49:44.610 に答える