Nicht druckbare Zeichen aus Strings in Python entfernen
Frage:
In Perl, Nicht druckbare Zeichen können mit dem Regex-Ausdruck s/[^[:print:]]//g entfernt werden. In Python wird die Klasse [:print:] jedoch nicht unterstützt. Wie können wir in Python eine ähnliche Funktionalität erreichen, die sowohl ASCII- als auch Unicode-Zeichen verarbeitet?
Antwort:
Aufgrund der Einschränkungen von Python bei der Erkennung der Druckbarkeit können wir unser eigenes Zeichen erstellen Klasse mit dem Unicodedata-Modul.
<code class="python">import unicodedata, re, itertools, sys # Generate a list of all characters all_chars = (chr(i) for i in range(sys.maxunicode)) # Category of control characters categories = {'Cc'} control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories) # Escape the control characters for regular expression matching control_char_re = re.compile('[%s]' % re.escape(control_chars)) # Function to remove control characters from a string def remove_control_chars(s): return control_char_re.sub('', s)</code>
Für Python 2:
<code class="python">import unicodedata, re, sys # Generate a list of all characters all_chars = (unichr(i) for i in xrange(sys.maxunicode)) # Category of control characters categories = {'Cc'} control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories) # Escape the control characters for regular expression matching control_char_re = re.compile('[%s]' % re.escape(control_chars)) # Function to remove control characters from a string def remove_control_chars(s): return control_char_re.sub('', s)</code>
Erweiterte Option:
Für Umfassendere Entfernung, zusätzliche Kategorien können einbezogen werden, obwohl dies Auswirkungen auf die Leistung haben kann.
Zeichenkategorien und -anzahlen:
Das obige ist der detaillierte Inhalt vonWie entferne ich nicht druckbare Zeichen aus Python-Strings?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!