だから、正規表現でgsubを使って、単語全体だけを置き換えてみました。ルールの1つは、 "be"をbに変更することです。しかし、私は個々の言葉のためにそれをしたいだけです。正規表現でgsubを使っているRuby
オリジナルの文字列:I really want to be the best at everything
変更された文字列:I really want to be the best at everything
目的の文字列:I really want to b the best at everything
次のコードでは、文字列の配列になりますと、 "B" に "可能" に変更する必要があります。
array = [
"Hey guys, can anyone teach me how to be cool?
I really want to be the best at everything,
you know what I mean? Tweeting is super fun you guys!!!!",
"OMG you guys, you won't believe how sweet my kitten is.
My kitten is like super cuddly and too cute to be believed right?",
"I'm running out of example tweets for you guys, which is weird,
because I'm a writer and this is just writing and I tweet all day.
For real, you guys. For real.",
"GUISEEEEE this is so fun! I'm tweeting for you guys and this tweet is
SOOOO long it's gonna be way more than you would think twitter can handle,
so shorten it up you know what I mean? I just can never tell how long to keep typing!",
"New game. Middle aged tweet followed by #youngPeopleHashTag Example:
Gotta get my colonoscopy and mammogram soon. Prevention is key! #swag"
]
rules = {
"hello" => "hi",
"too" => "2",
"to" => "2",
"two" => "2",
"for" => "4",
"four" => "4",
"be" => "b",
"you" => "u",
"at" => "@",
"and" => "&"
}
def substitutor(strings,subs)
strings.each_with_index do |string,index|
subs.each do |word,substitute|
strings[index].gsub!(/\bword\b/, substitute)
end
end
end
substitutor(array,rules)
私は正規表現を使用せずに置換されている場合、それは私にこれを与えるだろうが:I really want to b the bst at everything
メソッドの仮パラメータが間違っています。これは 'string'ですが、メソッド定義に従って' string'(複数形)にする必要があります。 –
あなたの現在の正規表現は、単語の両側にある単語の境界線を探しますが、正しく見えます。出力を生成するために実際に使用したコードを正確に表示してください。 –
'Regexp.union'はあなたの友人です。別のアプローチ:スペース上の単語に分割し、個別に再マップし、 'join'を単一の文字列に戻します。 – tadman