正規表現 (regex) は、パターンに基づいたテキストから必要な情報を引き出すことを目的としています。また、テキストの前処理につながるパターンベースのテキストの操作にも広く使用されており、次のようなデジタル スキルを実装するのに非常に役立ちます。 自然言語処理(NLP) 。
この記事では、それぞれが独自のシナリオである複数の例を示し、正規表現を使用してパターンを置換する方法を示します。を理解することが非常に必要ですre.sub()>
の方法re>
(正規表現) モジュールを使用して、指定されたソリューションを理解します。
のre.sub()>
メソッドは、指定された文字列に対してグローバル検索とグローバル置換を実行します。文字列内の特定のパターンを置換するために使用されます。この関数の引数は合計 5 つあります。
構文: re.sub(パターン、repl、文字列、カウント=0、フラグ=0)
文字列で比較するパラメーター:
pattern – 検索および置換されるパターン
repl – パターンを置換する文字列
string – パターンが格納されている変数の名前
count – 置換が実行される最大文字数
flags – 正規表現パターンの意味を変更するために使用されます
count>
そしてflags>
はオプションの引数です。
例 1: 特定のテキスト パターンの置換
この例では、指定されたテキスト パターンが検索され、文字列に置換されます。アイデアは、非常に標準的な形式を使用することです。re.sub()>
最初の 3 つの引数のみを持つメソッド。
以下は実装です。
# Python implementation of substituting a> # specific text pattern in a string using regex> > # importing regex module> import> re> > # Function to perform> # operations on the strings> def> substitutor():> > > # a string variable> > sentence1> => 'It is raining outside.'> > > # replacing text 'raining' in the string> > # variable sentence1 with 'sunny' thus> > # passing first parameter as raining> > # second as sunny, third as the> > # variable name in which string is stored> > # and printing the modified string> > print> (re.sub(r> 'raining'> ,> 'sunny'> , sentence1))> > > # a string variable> > sentence2> => 'Thank you very very much.'> > > # replacing text 'very' in the string> > # variable sentence2 with 'so' thus> > # passing parameters at their> > # appropriate positions and printing> > # the modified string> > print> (re.sub(r> 'very'> ,> 'so'> , sentence2))> > # Driver Code:> substitutor()> |
>
>出力:
It is sunny outside. Thank you so so much.>
必要なパターンが文字列内に何度存在しても、
re.sub()>
関数はそれらをすべて指定されたパターンに置き換えます。そのため、上の例では両方の「とても」が「だから」に置き換えられています。
例 2: 文字セットを特定の文字に置き換える
このタスクは、文字セットを指定された文字に置き換えることです。文字セットとは、文字の範囲を意味します。の中にre.sub()>
[ ](角括弧)内に文字セットを記述する方法です。
この例では、小文字の文字セット、つまり [a-z] は数字の 0 に置き換えられます。実装は以下のとおりです。
10の6乗
# Python implementation of substituting> # a character set with a specific character> > # importing regex module> import> re> > # Function to perform> # operations on the strings> def> substitutor():> > > # a string variable> > sentence> => '22 April is celebrated as Earth Day.'> > > # replacing every lower case characters> > # in the variable sentence with 0 and> > # printing the modified string> > print> (re.sub(r> '[a-z]'> ,> '0'> , sentence))> > # Driver Code:> substitutor()> |
>
>出力:
22 A0000 00 0000000000 00 E0000 D00.>
小文字と大文字の両方の文字セットを置き換える必要がある場合は、次の方法で大文字の文字セットを導入する必要があります: [a-zA-Z] または 効果的 その方法はフラグを使用することです。
例 3: 大文字と小文字を区別せずに文字セットを特定の文字に置換する
この例では、小文字と大文字の両方が指定された文字に置き換えられます。を使用すると、 フラグ 、このタスクは非常に簡単に実行できます。
のre.I>
フラグはreを表します。 無視する 。このフラグを導入することで、re.sub()>
メソッドを実行し、任意の 1 つの文字セット (小文字または大文字) を指定すると、タスクを完了できます。
以下は実装です。
# Python implementation of case-insensitive substitution> # of a character set with a specific character> > # importing regex module> import> re> > # Function to perform> # operations on the strings> def> substitutor():> > > # a string variable> > sentence> => '22 April is celebrated as Earth Day.'> > > # replacing both lowercase and> > # uppercase characters with 0 in> > # the variable sentence by using> > # flag and printing the modified string> > print> (re.sub(r> '[a-z]'> ,> '0'> , sentence, flags> => re.I))> > # Driver Code:> substitutor()> |
>
>出力:
22 00000 00 0000000000 00 00000 000.>
例 4: 特定の文字数まで置換を実行する
この例では、置換は文字列全体ではなく、特定の文字数まで行われます。このタイプの置換を実行するには、re.sub()>
メソッドには引数がありますcount>
。
この引数に数値を指定すると、置換が行われる文字数を制御できます。以下は実装です。
数学クラスJava
# Python implementation to perform substitution> # up to a certain number of characters> > # importing regex module> import> re> > # Function to perform> # operations on the strings> def> substitutor():> > > # a string variable> > sentence> => 'Follow your Passion.'> > > # case-insensitive substitution> > # on variable sentence upto> > # eight characters and printing> > # the modified string> > print> (re.sub(r> '[a-z]'> ,> '0'> , sentence,> 8> , flags> => re.I))> > # Driver Code:> substitutor()> |
>
>出力:
000000 00ur Passion.>
例 5: 短縮文字クラスを使用した置換とテキストの前処理
Regex モジュールは、テキストの前処理中に非常に一般的な文字セットに対して多くの短縮文字クラスを提供します。短縮文字クラスを使用すると、効率的なコードが作成され、すべての文字セットの範囲を覚えておく必要が少なくなります。
10mlをオンスに
速記文字クラスの詳細な説明とテキストの前処理のための Python での正規表現の記述方法を参照するには、クリックしてください。 ここ 。以下に、一般的に使用される短縮文字クラスの一部を示します。
w: 英数字と一致します
W: @、#、‘、+、%、– などの英数字以外の文字と一致します。
d: 数字文字と一致します
s: 空白文字と一致しますいくつかの構文の意味:
文字クラスまたはセットの後にプラス(+)記号を追加する: 前の文字クラスまたはセットを少なくとも 1 回以上繰り返します。文字クラスまたはセットの後にアスタリスク (*) 記号を追加: 前の文字クラスまたはセットを少なくとも 0 回以上繰り返します。
文字クラスまたはセットの前にキャレット (^) 記号を追加します。一致する位置は、その文字クラスまたは文字列の先頭で決定されます。
文字クラスまたはセットの後にドル($)記号を追加します。一致する位置は、その文字クラスまたは文字列の末尾で決定されます。
この例では、前述の短縮文字クラスを使用してテキストの置換と前処理を行い、クリーンでエラーのない文字列を取得する方法を示します。以下は実装です。
# Python implementation of Substitution using> # shorthand character class and preprocessing of text> > # importing regex module> import> re> > # Function to perform> # operations on the strings> def> substitutor():> > > # list of strings> > S> => [> '2020 Olympic games have @# been cancelled'> ,> > 'Dr Vikram Sarabhai was +%--the ISRO’s first chairman'> ,> > 'Dr Abdul Kalam, the father of India's missile programme'> ]> > > # loop to iterate every element of list> > for> i> in> range> (> len> (S)):> > > # replacing every non-word character with a white space> > S[i]> => re.sub(r> 'W'> ,> ' '> , S[i])> > > # replacing every digit character with a white space> > S[i]> => re.sub(r> 'd'> ,> ' '> , S[i])> > > # replacing one or more white space with a single white space> > S[i]> => re.sub(r> 's+'> ,> ' '> , S[i])> > > # replacing alphabetic characters which have one or more> > # white space before and after them with a white space> > S[i]> => re.sub(r> 's+[a-z]s+'> ,> ' '> , S[i], flags> => re.I)> > > # substituting one or more white space which is at> > # beginning of the string with an empty string> > S[i]> => re.sub(r> '^s+'> , '', S[i])> > > # substituting one or more white space which is at> > # end of the string with an empty string> > S[i]> => re.sub(r> 's+$'> , '', S[i])> > > # loop to iterate every element of list> > for> i> in> range> (> len> (S)):> > > # printing each modified string> > print> (S[i])> > # Driver Code:> substitutor()> |
>
>出力:
Olympic games have been cancelled Dr Vikram Sarabhai was the ISRO first chairman Dr Abdul Kalam the father of India missile programme>