Development Tip

.translate ()를 사용하여 Python 3.x의 문자열에서 구두점을 제거하는 방법은 무엇입니까?

yourdevel 2020. 11. 9. 21:16
반응형

.translate ()를 사용하여 Python 3.x의 문자열에서 구두점을 제거하는 방법은 무엇입니까?


.translate () 메서드를 사용하여 텍스트 파일에서 모든 구두점을 제거하고 싶습니다. Python 2.x에서는 잘 작동하는 것 같지만 Python 3.4에서는 아무것도하지 않는 것 같습니다.

내 코드는 다음과 같으며 출력은 입력 텍스트와 동일합니다.

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

메서드에 maketrans전달 하는 것을 사용하여 번역 테이블을 만들어야합니다 str.translate.

Python 3.1 이상에서는 maketrans이제 유형 str 대한 정적 메서드 이므로 원하는 각 구두점의 번역을 만드는 데 사용할 수 있습니다 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

python3.x에서는 다음을 사용하여 수행 할 수 있습니다.

import string
#make translator object
translator=str.maketrans('','',string.punctuation)
string_name=string_name.translate(translator)

str.translate의 호출 서명이 변경되었으며 분명히 매개 변수 deletechars가 제거되었습니다. 당신은 사용할 수 있습니다

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

대신 또는 다른 답변과 같이 테이블을 만드십시오.


세 가지 방법을 속도로 비교했습니다. (사전 컴파일 포함) translate보다 re.sub약 10 배 느립니다 . 그리고 약 3 배 str.replace보다 빠릅니다 re.sub. 에 의해 str.replaceI 의미 :

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

참고 URL : https://stackoverflow.com/questions/34293875/how-to-remove-punctuation-marks-from-a-string-in-python-3-x-using-translate

반응형