0
1

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.

Pythonで文字列から、日本語だけを消す方法

Last updated at Posted at 2023-01-13

課題

Pythonでの出力結果で、英語だけの情報を欲しいのに日本語の情報も混ざってしまうという課題がありました。
そこで出力結果の日本語と、日本語に関連する「。」と「、」を削除しようと考えました。
しかし文字列から日本語、「。」、「、」だけを消す方法が探しにくかったので、ここで共有させていただきます。

結論

re.sub()を使って、該当する文字列を空文字に置換する。

コード

import re

text = " 今日は本当に素晴らしい一日でした。朝起きたときから、心が躍っていました。今日は自分のやりたいことに挑戦する日です。Today was truly a wonderful day. From the moment I woke up this morning, my heart was racing. Today is the day I challenge myself to do what I want to do."

# 日本語と「。」「、」だけを削除
result = re.sub(r'[\u3040-\u309f\u30a0-\u30ff\u4e00-\u9faf|、|。]', "", text)
print(result)

# output>>> Today was truly a wonderful day. From the moment I woke up this morning, my heart was racing. Today is the day I challenge myself to do what I want to do.

注意点:
reという正規表現を扱うためのライブラリを忘れずにインポートしておく。

解説:
`[\u3040-\u309f\u30a0-\u30ff\u4e00-\u9faf]`は、日本語の文字を表すUnicodeのコード範囲を表します。
|、|。で、置換する対象として「、」「。」を追加しています。

↓Unicodeのコード範囲について、参考になったサイト

まとめ

今回はPythonで文字列から、日本語と、日本語と関連する「、」と「。」だけを消す方法を紹介しました!
日本語以外でも、「re.sub()を使って、該当する文字列を空文字に置換する。」という考え方は役に立つと思うので、ぜひ使ってみてください!

少しでもお役に立てれば、幸いです!
最後までお読みいただき、ありがとうございました!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?