質問
文字列からすべての数字を削除しようとしています。 ただし、次のコードでは、任意の単語に含まれる数字も削除されるため、明らかにそれは望ましくありません。 私は多くの正規表現を試してみましたが成功しませんでした。
ありがとう!
s = "This must not b3 delet3d, but the number at the end yes 134411"
s = re.sub("\d+", "", s)
print s
結果:
これは削除してはなりませんが、最後の数字は削除します
解決
\ d +の前にスペースを追加します。
>>> s = "This must not b3 delet3d, but the number at the end yes 134411"
>>> s = re.sub(" \d+", " ", s)
>>> s
'This must not b3 delet3d, but the number at the end yes '
編集:コメントを見た後、より完全な回答を作成することにしました。これはすべてのケースに当てはまると思います。
s = re.sub("^\d+\s|\s\d+\s|\s\d+<*>quot;, " ", s)
他のヒント
これを試してください:
"\b\d+\b"
別の単語の一部ではない数字のみに一致します。
\ s
の使用は、タブなどを処理しないため、あまり良くありません。より良い解決策の最初のカットは次のとおりです。
re.sub(r"\b\d+\b", "", s)
\ b
は通常、文字列のバックスペースエスケープであるため、パターンは生の文字列であり、代わりに特殊な単語境界正規表現エスケープが必要です。少し手の込んだバージョンは次のとおりです。
re.sub(r"$\d+\W+|\b\d+\b|\W+\d+<*>quot;, "", s)
文字列の先頭/末尾に数字がある場合、先頭/末尾の空白を削除しようとします。 「トライ」と言います末尾に複数の数字がある場合、まだいくつかのスペースがあるためです。
行頭の数字列も処理するには:
s = re.sub(r"(^|\W)\d+", "", s)
番号が常に文字列の末尾にある場合は、次を試してください: re.sub(&quot; \ d + $&quot ;,&quot;&quot ;, s)
それ以外の場合は、試すことができます re.sub(&quot;(\ s)\ d +(\ s)&quot;、&quot; \ 1 \ 2&quot;、s)
1つまたは2つのスペースのみを保持するように後方参照を調整できます(\ sは任意の白い区切りに一致します)
非正規表現ソリューション:
>>> s = "This must not b3 delet3d, but the number at the end yes 134411"
>>> " ".join([x for x in s.split(" ") if not x.isdigit()])
'This must not b3 delet3d, but the number at the end yes'
&quot;で分割&quot;
、および < code> str()。isdigit() 、それらを再び結合します。より詳細に(リスト内包表記を使用しない):
words = s.split(" ")
non_digits = []
for word in words:
if not word.isdigit():
non_digits.append(word)
" ".join(non_digits)
実際の状況がどのように見えるかわかりませんが、ほとんどの答えは負の数や小数を処理できないようです
re.sub(r&quot;(\ b | \ s + \-?| ^ \-?)(\ d + | \ d * \。\ d +)\ b&quot;、&quot;&quot;)コード>
上記は、次のようなものも処理する必要があります。
&quot;これはb3 delet3dであってはならず、最後の数字はyes -134.411&quot;
しかし、これはまだ不完全です-おそらく、解析する必要があるファイルで見つけることができるもののより完全な定義が必要です。
編集:使用しているロケール/文字セットに応じて '\ b'が変わることにも注意する必要がありますので、少し注意する必要があります。
これを試すことができます
s = "This must not b3 delet3d, but the number at the end yes 134411"
re.sub("(\s\d+)","",s)
結果:
'This must not b3 delet3d, but the number at the end yes'
同じルールが適用されます
s = "This must not b3 delet3d, 4566 but the number at the end yes 134411"
re.sub("(\s\d+)","",s)
結果:
<*>>>>s = "This must not b3 delet3d, but the number at the end yes 134411"
>>>s = re.sub(r"\d*<*>quot;, "", s)
>>>s
&quot;これはb3 delet3dではなく、末尾の数字はい&quot;
これにより、文字列の末尾の数値が削除されます。