23

Pythonの文字列で、すべての句読文字を「」に置き換えたい(削除しない)ようにします。

次のフレーバーの効率的なものはありますか?

text = text.translate(string.maketrans("",""), string.punctuation)
4

6 に答える 6

48

この回答はPython2用であり、ASCII文字列に対してのみ機能します。

文字列モジュールには、句読文字のリストと「maketrans」関数の2つが含まれています。これらの使用方法は次のとおりです。

import string
replace_punctuation = string.maketrans(string.punctuation, ' '*len(string.punctuation))
text = text.translate(replace_punctuation)
于 2012-09-15T13:23:49.027 に答える
20

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'
于 2012-09-15T13:21:25.020 に答える
2

この回避策は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' 
于 2018-07-23T14:41:31.063 に答える
2

句読文字の広範なリストを介して含めるのではなく、正規表現の除外に依存する、より堅牢なソリューションがあります。

import re
print(re.sub('[^\w\s]', '', 'This is, fortunately. A Test! string'))
#Output - 'This is fortunately A Test string'

正規表現は、英数字または空白文字ではないものをすべてキャッチします

于 2018-08-02T14:12:46.060 に答える
0

に置き換え''?ます。

;すべてを''に変換することと、すべてを削除することの違いは何;ですか?

これがすべてを削除すること;です:

s = 'dsda;;dsd;sad'
table = string.maketrans('','')
string.translate(s, table, ';')

そして、あなたは翻訳であなたの取り替えをすることができます。

于 2012-09-15T13:24:55.120 に答える
0

私の特定の方法で、句読点リストから「+」と「&」を削除しました。

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

于 2017-08-17T19:05:13.743 に答える