.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
이제 유형에 대한 정적 기호이므로, 이를 사용하여 원하는 각 구두점의 변환을 만들 수 있습니다.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
str.translate의 호출 서명이 변경되었으며 매개 변수 삭제 문자가 제거되었습니다.사용할 수 있습니다.
import re
fline = re.sub('['+string.punctuation+']', '', fline)
대신 다른 답변에 표시된 것처럼 표를 작성합니다.
python 3.x에서는 다음을 사용하여 수행할 수 있습니다.
import string
#make translator object
translator=str.maketrans('','',string.punctuation)
string_name=string_name.translate(translator)
나는 단지 속도별로 세 가지 방법을 비교했을 뿐입니다. translate
보다 느림re.sub
(사전 편찬과 함께) 약 10번 만에.그리고.str.replace
보다 빠름re.sub
3번 정도에.타고str.replace
내 말은:
for ch in string.punctuation:
s = s.replace(ch, "'")
답변이 늦었지만 python >= 3.6에서 모든 구두점을 제거하려면 다음을 사용할 수도 있습니다.
import re, string
clean_string = re.sub(rf"[{string.punctuation}]", "", dirty_string)
Python 3.6에서는 다음을 사용하여 구두점을 제거할 수 있습니다.
import string
your_string.translate(str.maketrans('', '',string.punctuation))
.maketrans() 메서드는 세 개의 인수를 사용합니다. 첫 번째 두 개는 빈 문자열이고 세 번째는 제거할 구두점 목록입니다.이것은 모든 구두점을 '없음'으로 대체하는 기능을 알려줍니다.
또한 다음을 실행하여 문자열 라이브러리와 함께 제공되는 구두점 속성을 볼 수 있습니다.
print(string.punctuation)
언급URL : https://stackoverflow.com/questions/34293875/how-to-remove-punctuation-marks-from-a-string-in-python-3-x-using-translate
'programing' 카테고리의 다른 글
예외가 있는 Python 유형 암시 (0) | 2023.05.07 |
---|---|
VBA의 멀티스레딩 (0) | 2023.05.07 |
날짜 범위 간의 postgresql 쿼리 (0) | 2023.05.07 |
python3.3에서 docx를 가져올 때ImportError 오류가 발생했습니다. 'exceptions'라는 이름의 모듈이 없습니다. (0) | 2023.05.07 |
try {return x; } 마지막으로 {x = null; } 문에서 실제로 어떤 일이 발생합니까? (0) | 2023.05.07 |