Измените каждое слово в абзаце с помощью Ruby - PullRequest
1 голос
/ 08 февраля 2011

Итак, я пишу код на 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.

И мне нужно изменить каждое слово в абзаце, не меняя структуру.Моя первоначальная идея состояла в том, чтобы просто разбить пробел и затем снова присоединиться к нему, но проблема в том, что вы также получаете пунктуацию.Если вы разделите текст так, чтобы вы просто получили слово, трудно присоединиться, потому что вы не знаете правильную пунктуацию.

Есть ли лучшие способы сделать это, чем традиционная комбинация split, map, join?Или, может быть, просто хорошее регулярное выражение, поэтому легко присоединиться?

Ответы [ 2 ]

3 голосов
/ 08 февраля 2011

Я бы сопоставил слова между границами слов с помощью регулярного выражения, чтобы избежать влияния на знаки препинания или пробелы, например ::10000

s = "This is a test, ok?  Yes, fine!"
s.gsub!(/\b(\w+)\b/) {|x| "_#{x}_"}
s = "_This_ _is_ _a_ _test_, _ok_?  _Yes_, _fine_!"
3 голосов
/ 08 февраля 2011

Используйте 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') }

result:

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 будет работать без регулярного выражения, но вы понимаете, что это.

...