0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

正規表現を使って連続して出てくる部分文字列をひとつにする

Last updated at Posted at 2018-03-28

ある連続して出てくる部分文字列をひとつにしたい
例えば、以下のような文字列があったとき。
「お願いがあるんだけど……友人代表のスピーチ、やってくれないかな?」<EOS><EOS>
これを:point_down_tone1::point_down_tone1::point_down_tone1:にしたい
「お願いがあるんだけど……友人代表のスピーチ、やってくれないかな?」<EOS>
繰り返しでてくる<EOS>をひとつにするには
re.sub("(?<=部分文字列)部分文字列", "", 文字列)

import re

sample = "「お願いがあるんだけど……友人代表のスピーチ、やってくれないかな?」<EOS><EOS>"
result = re.sub("(?<=<EOS>)<EOS>", "", sample)
print(result)
# 結果
# 「お願いがあるんだけど……友人代表のスピーチ、やってくれないかな?」<EOS>

他の例

sample = "「お願いがあるんだけど……友人代表のスピーチ、やってくれないかな?」<EOS><EOS><EOS>"
result = re.sub("(?<=<EOS>)<EOS>", "", sample)
print(result)
# 結果
# 「お願いがあるんだけど……友人代表のスピーチ、やってくれないかな?」<EOS>

sample = "「お願いがあるんだけど……友人代表のスピーチ、<EOS><EOS>やってくれないかな?」<EOS><EOS><EOS>"
result = re.sub("(?<=<EOS>)<EOS>", "", sample)
print(result)
# 結果
# 「お願いがあるんだけど……友人代表のスピーチ、<EOS>やってくれないかな?」<EOS>

コメントより

sample = "「お願いがあるんだけど……友人代表のスピーチ<EOS><EOS>、やってくれないかな?」<EOS><EOS>"
result = re.sub("(<EOS>)+", "<EOS>", sample)
print(result)
# 結果
# 「お願いがあるんだけど……友人代表のスピーチ<EOS>、やってくれないかな?」<EOS>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?