>  기사  >  백엔드 개발  >  Python 문자열에서 인쇄할 수 없는 문자를 제거하는 방법은 무엇입니까?

Python 문자열에서 인쇄할 수 없는 문자를 제거하는 방법은 무엇입니까?

Susan Sarandon
Susan Sarandon원래의
2024-10-22 06:58:30305검색

How to Remove Non-Printable Characters from Python Strings?

Python의 문자열에서 인쇄할 수 없는 문자 제거

질문:

Perl에서는, 인쇄할 수 없는 문자는 정규식 s/[^[:print:]]//g를 사용하여 제거할 수 있습니다. 그러나 Python에서는 [:print:] 클래스가 지원되지 않습니다. ASCII와 유니코드 문자를 모두 처리하는 Python에서 유사한 기능을 어떻게 얻을 수 있습니까?

답변:

인쇄 가능성 감지에 대한 Python의 제한으로 인해 자체 문자를 구성할 수 있습니다. unicodedata 모듈을 사용하는 클래스입니다.

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

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>

확장 옵션:

의 경우 보다 포괄적인 제거를 위해서는 추가 범주를 포함할 수 있지만 성능에 영향을 미칠 수 있습니다.

문자 범주 및 개수:

  • 참조(컨트롤): 65
  • Cf(형식): 161
  • Cs(대리): 2048
  • Co(개인 사용): 137468
  • Cn(할당되지 않음): 836601

위 내용은 Python 문자열에서 인쇄할 수 없는 문자를 제거하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.