1
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 1 year has passed since last update.

neologdnによる正規化の際にスペースを一つ残す方法

Last updated at Posted at 2024-04-11

 正規化ライブラリneologdnを文字列整理で使う際に、スペースをすべて消さずに半角スペースを一つ残す方法です。

import neologdn

text = "整理   したい   文章!"

normalized_text = neologdn.normalize(text)

print(normalized_text)
// 整理したい文章!

neologdnは
「ひらがな・全角カタカナ・半角カタカナ・漢字・全角記号」間に含まれるスペースと
「ひらがな・全角カタカナ・半角カタカナ・漢字・全角記号」と「半角英数字」の間に含まれるスペース
はすべて削除します。

一つ半角スペースを残したい際は

import neologdn
import re


# 元のテキスト
text = "整理   したい   文章!"

# 単語間のスペースを一時的に特定の文字列に置換
replaced_text = re.sub(r'\s+', '<w>', text)

# neologdnを使用して正規化
normalized_text = neologdn.normalize(replaced_text)

# 置換した文字列を空白に戻す
final_text = re.sub(r'<w>', ' ', normalized_text)


print(final_text)
# 整理 したい 文章!

スペースを一度別の文字列に置換し、neologdnをかけた後に再び置換することで一つだけ残すことができます。

1
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
1
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?