2015-12-15 19 views
29

.translate()メソッドを使用してテキストファイルからすべての句読点を削除します。 Python 2.xではうまくいくようですが、Python 3.4では何もしていないようです。.translate()を使ってPython 3.xの文字列から句読点を削除するには?

私のコードは以下の通りです。出力は入力テキストと同じです。

import string 
fhand = open("Hemingway.txt") 
for fline in fhand: 
    fline = fline.rstrip() 
    print(fline.translate(string.punctuation)) 

答えて

8

str.translateの呼び出しシグネチャが変更され、明らかにパラメータdeletecharsが削除されました。代わりに

import re 
fline = re.sub('['+string.punctuation+']', '', fline) 

を使用するか、他の回答のように表を作成することができます。

+0

パーフェクト、優れた作品! – cybujan

+0

(@birryreeの例(http://stackoverflow.com/a/34294398/1656850)は、string.translateの廃止勅令に同意しません。 – boardrider

+0

あなたは正しいです。その点について私は誤解していました。コールシグネチャのみが変更されました。str.translateはテーブルをパラメータとして取り、deletecharsを削除しません(birryreeの回答を参照)。私はそれに応じて私の答えを編集します。 – elzell

84

maketransを使用してstr.translateメソッドに渡す変換テーブルを作成する必要があります。

Python 3.1以降では、maketransstatic-method on the str typeになりました。これを使用して、句読点の翻訳をNoneにすることができます。

import string 

# Thanks to Martijn Pieters for this improved version 

# This uses the 3-argument version of str.maketrans 
# with arguments (x, y, z) where 'x' and 'y' 
# must be equal-length strings and characters in 'x' 
# are replaced by characters in 'y'. 'z' 
# is a string (string.punctuation here) 
# where each character in the string is mapped 
# to None 
translator = str.maketrans('', '', string.punctuation) 

# This is an alternative that creates a dictionary mapping 
# of every character from string.punctuation to None (this will 
# also work) 
#translator = str.maketrans(dict.fromkeys(string.punctuation)) 

s = 'string with "punctuation" inside of it! Does this work? I hope so.' 

# pass the translator to the string's translate method. 
print(s.translate(translator)) 

これは、出力すべきは:

string with punctuation inside of it Does this work I hope so 
+1

これはうまくいきます。残念ながら、このトピックのトップのGoogle検索結果は推奨されなくなりました。遅くなったり、追跡が難しくなったりします。 – rurp

+1

'string.punctuation'には引用符が含まれていないようです。 'string.punctuation'のキーとユーザー指定の文字でトリミングするには、このコードをどのように微調整しますか?あるか声明? –

+1

@ArashHowaida 'string.punctuation'は二重引用符と二重引用符を含みます - 私の例でも二重引用符は取り除きます。 'str.punctuation'に加えて削除されるものをカスタマイズしたい場合は、単に' string.punctuation'を 'translator = str.maketrans({key:string in key .punctuation + 'abc'}) '文字列' a'、 'b'、または' c'の句読点や出現箇所を削除したい場合に使用します。 – birryree

0

私はスピードによる3つのメソッドを比較しました。 translateは、約10倍でre.sub(プリコンパイルあり)よりも遅い。 str.replaceは約3倍でre.subより高速です。 str.replaceことで私は意味:

for ch in string.punctuation:                          
    s = s.replace(ch, "'") 
+1

私はあなたが間違っていると思う私はPython 3.6.0b4でhttp://stackoverflow.com/a/266162/4249707からテストを実行する(python3の翻訳テスト部分で採用されている)、何年も前にsucksを置き換える。私の結果 - セット:2.7033574236556888 正規表現:0.9831533581018448 翻訳:1.837449918501079 置き換え:5.498765277676284 –

4

python3.xで、それが使用して行うことができます。

import string 
#make translator object 
translator=str.maketrans('','',string.punctuation) 
string_name=string_name.translate(translator) 
関連する問題