5

コードを使用して、句読点からテキスト行を削除します。

line = line.rstrip("\n")
line = line.translate(None, string.punctuation)

問題は、次のような単語が次のようdoesn'tになることdoesntです。単語間の句読点のみを削除したいのですが、その方法がわかりません。これについてどうすればよいですか?

編集:関数を使用することを考えましstrip()たが、それは文全体の左右の末尾にのみ有効です。

例えば:

Isn't ., stackoverflow the - best ?

次のようになる必要があります。

Isn't stackoverflow the best

現在の出力の代わりに:

Isnt stackoverflow the best
4

2 に答える 2

11

単語をスペースで区切られた文字のグループと見なすと仮定します。

>>> from string import punctuation
>>> line = "Isn't ., stackoverflow the - best ?"
>>> ' '.join(word.strip(punctuation) for word in line.split() 
             if word.strip(punctuation))
"Isn't stackoverflow the best"

また

>>> line = "Isn't ., stackoverflow the - best ?"
>>> ' '.join(filter(None, (word.strip(punctuation) for word in line.split())))
"Isn't stackoverflow the best"
于 2013-04-01T09:12:27.300 に答える
-1
line = line.translate(None, string.punctuation.replace('\'', ''))

これはあなたが欲しいものですか?

于 2013-04-01T09:28:17.017 に答える