2016-05-05 10 views
1

Ich versuche Interpunktion aus dem Text unten zu entfernen. Ich konvertiere den Text in Unicode, um später mögliche Kodierungsprobleme zu vermeiden.übersetzen Funktion und Unicode-Konvertierung

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 

Allerdings verursacht die Übersetzungsfunktion unerklärlicherweise einen Fehler über die Anzahl der Argumente.

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

Das Entfernen des Unicode-Konvertierungsschritts stellt die korrekte Ausführung sicher, ist jedoch unabdingbar und ebenso die Übersetzungsfunktion. Wie kann ich mein Ziel fehlerfrei erreichen und beide Funktionen behalten?

Antwort

2

str.translate() und unicode.translate() nehmen verschiedene Argumente. Dies verletzt LSP, ist aber angesichts der großen Anzahl von Zeichen in Unicode-Zeichenfolgen erforderlich.

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

das sein wird, weil Sie unicode.translate() anrufen, nicht str.translate().

>>> 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. 

Dies sollte die gleiche Arbeit, dh Satzzeichen entfernen:

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

By the way, für str Objekte, können Sie einfach tun:

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

dh wenn None ist Für die Übersetzungstabelle angegeben, werden die Zeichen im zweiten Argument entfernt.