2016-05-05 4 views
1

以下のテキストから句読点を削除しようとしています。私は後で出てくるエンコードの問題を避けるために、テキストをUnicodeに変換しています。translate関数とユニコード変換

import string 
st = "I absolutely go incredibly far. Zach went fast over crab sand land.\n\nThis is a new paragraph. This is the second sentence in that paragraph. This exsquisite utterance is indubitably the third sentence of this fine text.\n\nPlagiarism detection can be operationalized by decomposing a document into natural sections, such as sentences, chapters, or topically related blocks, and analyzing the variance of stylometric features for these sections. In this regard the decision problems in Sect. 1.2 are of decreasing complexity: instances of AVFIND are comprised of both a selection problem (finding suspicious sections) and an AVOUTLIER problem; instances of AVBATCH are a restricted variant of AVOUTLIER since one has the additional knowledge that all elements of a batch are (or are not) outliers at the same time." 
st = unicode(st, errors = 'ignore') 
for word in st.split(' '): 
    wd = word.lower().translate(string.maketrans("",""), string.punctuation) 
    print wd 

しかし、translate関数は、引数の数についてエラーを起こす可能性があります。

TypeError: translate() takes exactly one argument (2 given) 

ユニコード変換ステップを削除すると、正しい実行が保証されますが、変換機能も必須です。どのようにしてエラーなく目標を達成し、両方の機能を維持することができますか?

答えて

2

str.translate()およびunicode.translate()は異なる引数をとります。これはLSPに違反しますが、Unicode文字列で使用可能な文字数が多い場合は必要です。あなたは、str.translate()unicode.translate()しない呼び出しているためだろう

word.lower().translate(dict((x, None) for x in string.punctuation)) 
2

>>> help(unicode.translate) 
translate(...) 
    S.translate(table) -> unicode 

    Return a copy of the string S, where all characters have been mapped 
    through the given translation table, which must be a mapping of 
    Unicode ordinals to Unicode ordinals, Unicode strings or None. 
    Unmapped characters are left untouched. Characters mapped to None 
    are deleted. 

これは、同じように動作するはずです、つまり句読点の文字を削除します。

wd = word.lower().translate({ord(c): None for c in string.punctuation}) 

ところで、strオブジェクトに対して、あなたは、単にこれを行うことができます。

wd = word.lower().translate(None, string.punctuation) 

すなわちNoneがあるとき変換テーブルに指定されている場合、2番目の引数の文字は削除されます。

関連する問題