Pythonの文字列で、すべての句読文字を「」に置き換えたい(削除しない)ようにします。
次のフレーバーの効率的なものはありますか?
text = text.translate(string.maketrans("",""), string.punctuation)
この回答はPython2用であり、ASCII文字列に対してのみ機能します。
文字列モジュールには、句読文字のリストと「maketrans」関数の2つが含まれています。これらの使用方法は次のとおりです。
import string
replace_punctuation = string.maketrans(string.punctuation, ' '*len(string.punctuation))
text = text.translate(replace_punctuation)
Pythonで文字列から句読点を取り除くための最良の方法からの修正されたソリューション
import string
import re
regex = re.compile('[%s]' % re.escape(string.punctuation))
out = regex.sub(' ', "This is, fortunately. A Test! string")
# out = 'This is fortunately A Test string'
この回避策はPython3で機能します。
import string
ex_str = 'SFDF-OIU .df !hello.dfasf sad - - d-f - sd'
#because len(string.punctuation) = 32
table = str.maketrans(string.punctuation,' '*32)
res = ex_str.translate(table)
# res = 'SFDF OIU df hello dfasf sad d f sd'
句読文字の広範なリストを介して含めるのではなく、正規表現の除外に依存する、より堅牢なソリューションがあります。
import re
print(re.sub('[^\w\s]', '', 'This is, fortunately. A Test! string'))
#Output - 'This is fortunately A Test string'
正規表現は、英数字または空白文字ではないものをすべてキャッチします
に置き換え''?
ます。
;
すべてを''に変換することと、すべてを削除することの違いは何;
ですか?
これがすべてを削除すること;
です:
s = 'dsda;;dsd;sad'
table = string.maketrans('','')
string.translate(s, table, ';')
そして、あなたは翻訳であなたの取り替えをすることができます。
私の特定の方法で、句読点リストから「+」と「&」を削除しました。
all_punctuations = string.punctuation
selected_punctuations = re.sub(r'(\&|\+)', "", all_punctuations)
print selected_punctuations
str = "he+llo* ithis& place% if you * here @@"
punctuation_regex = re.compile('[%s]' % re.escape(selected_punctuations))
punc_free = punctuation_regex.sub("", str)
print punc_free
結果:ここにいる場合はhe + llo ithis&place