2
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 3 years have passed since last update.

【Python Tips】文中の数字を0にする

2
Posted at

今回は文中の数字を0に変える処理を行います。

利用シーン

例えばネットニュースの記事を政治・経済・エンタメ・スポーツなどに分類する場合などに使われます。

記事のカテゴリを分類する際に数字の情報はあまり重要ではないため外して良いと考えられるからです。

環境

Google Colaboratory

コード

1.モジュールreをインポート

正規表現操作を行うためのモジュールであるreをインポートする

import re

2.関数を定義

normalize_numberという関数を定義します。
2行目ではモジュールreのsub()関数を活用します。

re.sub()では第一引数に正規表現パターン、第二引数に置換先文字列、第三引数に処理対象の文字列を指定します。

今回の場合
- 第一引数:1つ以上の連続した変数を
- 第二引数:0に変える
- 第三引数:textで

def normalize_number(text):
  replaced_text = re.sub(r'\d+','0',text)
  return replaced_text

3.置換したい文字列を設定

text ="1万8100・24ドル"
normalize_number(text)

コードはGoogle Cobabに書きましたので、ご参照いただけましたら幸いです。

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