programing

문자열에서 구두점을 제거하는 가장 좋은 방법

new-time 2020. 2. 9. 19:58
반응형

문자열에서 구두점을 제거하는 가장 좋은 방법


다음보다 간단한 방법이 있어야합니다.

import string s = "string. With. Punctuation?" # Sample string  out = s.translate(string.maketrans("",""), string.punctuation) 

있습니까?


효율성 측면에서 이길 수는 없습니다

s.translate(None, string.punctuation) 

더 높은 버전의 Python의 경우 다음 코드를 사용하십시오.

s.translate(str.maketrans('', '', string.punctuation)) 

C에서 조회 테이블을 사용하여 원시 문자열 작업을 수행하고 있습니다.이를 능가하는 것은 아니지만 자신의 C 코드를 작성하는 것입니다.속도가 걱정되지 않으면 다른 옵션은 다음과 같습니다.

exclude = set(string.punctuation) s = ''.join(ch for ch in s if ch not in exclude) 

이것은 각 문자로 s.replace보다 빠르지 만 아래 타이밍에서 볼 수 있듯이 정규 표현식이나 string.translate와 같은 순수하지 않은 파이썬 접근법은 수행하지 않습니다. 이러한 유형의 문제의 경우 가능한 낮은 수준에서 문제를 해결하면 효과가 있습니다.타이밍 코드 :

import re, string, timeit  s = "string. With. Punctuation" exclude = set(string.punctuation) table = string.maketrans("","") regex = re.compile('[%s]' % re.escape(string.punctuation))  def test_set(s): return ''.join(ch for ch in s if ch not in exclude)  def test_re(s): # From Vinko's solution, with fix. return regex.sub('', s)  def test_trans(s): return s.translate(table, string.punctuation)  def test_repl(s): # From S.Lott's solution for c in string.punctuation: s=s.replace(c,"") return s  print "sets :",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000) print "regex :",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000) print "translate :",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000) print "replace :",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000) 

결과는 다음과 같습니다.

sets : 19.8566138744 regex : 6.86155414581 translate : 2.12455511093 replace : 28.4436721802 

정규 표현식은 알고 있다면 충분히 간단합니다.

import re s = "string. With. Punctuation?" s = re.sub(r'[^\w\s]','',s) 

사용법의 편의를 위해 Python 2와 Python 3의 문자열에서 스트라이핑 구두점에 대한 메모를 요약합니다. 자세한 설명은 다른 답변을 참조하십시오.


파이썬 2

import string  s = "string. With. Punctuation?" table = string.maketrans("","") new_s = s.translate(table, string.punctuation) # Output: string without punctuation 

파이썬 3

import string  s = "string. With. Punctuation?" table = str.maketrans() new_s = s.translate(table) # Output: string without punctuation 

myString.translate(None, string.punctuation) 

나는 보통 다음과 같은 것을 사용합니다 :

>>> s = "string. With. Punctuation?" # Sample string >>> import string >>> for c in string.punctuation: ... s= s.replace(c,"") ... >>> s 'string With Punctuation' 

string.punctuation

ASCII

만입니다

! 더 정확한 (그러나 훨씬 더 느린) 방법은 유니 코드 데이터 모듈을 사용하는 것입니다.

# -*- coding: utf-8 -*- from unicodedata import category s = u'String — with - «punctation »...' s = ''.join(ch for ch in s if category(ch)[0] != 'P') print 'stripped', s 

가족과 더 친숙하다면 더 단순 할 필요는 없지만 다른 방법입니다.

import re, string s = "string. With. Punctuation?" # Sample string  out = re.sub('[%s]' % re.escape(string.punctuation), '', s) 

Python 3

str

또는 Python 2

unicode

값의

str.translate()

경우 사전 만 사용합니다. 해당 매핑에서 코드 포인트 (정수)가 조회되고 매핑 된 항목

None

이 제거됩니다.그런 다음 구두점을 제거하려면 다음을 사용하십시오.

import string  remove_punct_map = dict.fromkeys(map(ord, string.punctuation)) s.translate(remove_punct_map) 

 

dict.fromkeys()클래스 메소드는

사소한 모든 설정 값을 매핑을 만들 수 있습니다

None

키의 순서에 따라.ASCII 문장 부호뿐만 아니라

모든

문장 부호 를 제거하려면 테이블이 약간 커야합니다.

JF Sebastian의 답변

(Python 3 버전)을 참조하십시오 .

import unicodedata import sys  remove_punct_map = dict.fromkeys(i for i in range(sys.maxunicode) if unicodedata.category(chr(i)).startswith('P')) 

string.punctuation

현실 세계에서 일반적으로 사용되는 많은 문장 부호를 그리워합니다. 비 ASCII 구두점에 적합한 솔루션은 어떻습니까?

import regex s = u"string. With. Some・Really Weird、Non?ASCII。 「(Punctuation)」?" remove = regex.compile(ur'[\p|\p|\p|\p|\p]+', regex.UNICODE) remove.sub(u" ", s).strip() 

개인적으로, 이것이 파이썬의 문자열에서 구두점을 제거하는 가장 좋은 방법이라고 생각합니다.

  • 모든 유니 코드 문장 부호를 제거합니다
  • 쉽게 수정할 수 있습니다. 예를 들어 \문장 부호를 제거하려는 경우를 제거 할 수 있지만 기호는 다음과 같이 유지하십시오 $.
  • 유지하려는 항목과 제거하려는 항목을 구체적으로 지정할 수 있습니다 (예 : \대시 만 제거).
  • 이 정규식은 공백도 정규화합니다. 탭, 캐리지 리턴 및 기타 홀수를 멋진 단일 공백에 매핑합니다.

이것은

Wikipedia에서 더 많은 것을 읽을 수

있는 유니 코드 문자 속성을 사용합니다 .


아직이 답변을 보지 못했습니다. 정규식을 사용하십시오. 단어 문자 (

\w

) 및 숫자 문자 (

\d

) 이외의 모든 문자 공백 문자 (

\s

)를 제거합니다.

import re s = "string. With. Punctuation?" # Sample string  out = re.sub(ur'[^\w\d\s]+', '', s) 

다음은 Python 3.5의 한 줄짜리입니다.

import string "l*ots! o(f. p@u)n[c}t]u[a'ti\"on#$^?/".translate(str.maketrans()) 


이것은 최선의 해결책은 아니지만 이것이 내가 한 방법입니다.

import string f = lambda x: ''.join([i for i in x if i not in string.punctuation]) 

내가 쓴 함수는 다음과 같습니다. 매우 효율적이지는 않지만 간단하지만 원하는 구두점을 추가하거나 제거 할 수 있습니다.

def stripPunc(wordList): """Strips punctuation from list of words""" puncList = [".",";",":","!","?","/","\\",",","#","@","$","&",")","(","\""] for punc in puncList: for word in wordList: wordList=[word.replace(punc,'') for word in wordList] return wordList 

정규식이없는 솔루션이 있습니다.

import string  input_text = "!where??and!!or$$then:)" punctuation_replacer = string.maketrans(string.punctuation, ' '*len(string.punctuation))  print ' '.join(input_text.translate(punctuation_replacer).split()).strip()  Output>> where and or then 
  • 문장 부호를 공백으로 바꿉니다.
  • 단어 사이의 여러 공백을 단일 공백으로 교체
  • strip ()을 사용하여 후행 공백을 제거하십시오.

업데이트와 마찬가지로 Python 3에서 @Brian 예제를 다시 작성하고 함수 내부에서 정규식 컴파일 단계를 이동하도록 변경했습니다. 여기에서 제 생각은 기능을 작동시키는 데 필요한 모든 단일 단계에 대한 시간이었습니다. 아마도 분산 컴퓨팅을 사용하고 있으며 직원간에 정규식 객체를 공유 할 수 없으며

re.compile

각 작업자마다 단계를 수행 해야합니다 . 또한 파이썬 3에 대해 두 가지 다른 구현의 maketrans 시간을 궁금합니다.

table = str.maketrans() 

vs

table = str.maketrans('', '', string.punctuation) 

또한 set을 사용하는 또 다른 방법을 추가하여 교차 횟수를 활용하여 반복 횟수를 줄였습니다.이것은 완전한 코드입니다.

import re, string, timeit  s = "string. With. Punctuation"   def test_set(s): exclude = set(string.punctuation) return ''.join(ch for ch in s if ch not in exclude)   def test_set2(s): _punctuation = set(string.punctuation) for punct in set(s).intersection(_punctuation): s = s.replace(punct, ' ') return ' '.join(s.split())   def test_re(s): # From Vinko's solution, with fix. regex = re.compile('[%s]' % re.escape(string.punctuation)) return regex.sub('', s)   def test_trans(s): table = str.maketrans() return s.translate(table)   def test_trans2(s): table = str.maketrans('', '', string.punctuation) return(s.translate(table))   def test_repl(s): # From S.Lott's solution for c in string.punctuation: s=s.replace(c,"") return s   print("sets :",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000)) print("sets2 :",timeit.Timer('f(s)', 'from __main__ import s,test_set2 as f').timeit(1000000)) print("regex :",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000)) print("translate :",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000)) print("translate2 :",timeit.Timer('f(s)', 'from __main__ import s,test_trans2 as f').timeit(1000000)) print("replace :",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000)) 

이것은 내 결과입니다.

sets : 3.1830138750374317 sets2 : 2.189873124472797 regex : 7.142953420989215 translate : 4.243278483860195 translate2 : 2.427158243022859 replace : 4.579746678471565 

>>> s = "string. With. Punctuation?" >>> s = re.sub(r'[^\w\s]','',s) >>> re.split(r'\s*', s)   ['string', 'With', 'Punctuation'] 

import re s = "string. With. Punctuation?" # Sample string  out = re.sub(r'[^a-zA-Z0-9\s]', '', s) 

하나의 라이너는 매우 엄격한 경우에 도움이 될 수 있습니다.

''.join([c for c in s if c.isalnum() or c.isspace()]) 

#FIRST METHOD #Storing all punctuations in a variable  punctuation='!?,.:;"\')(_-' newstring='' #Creating empty string word=raw_input("Enter string: ") for i in word: if(i not in punctuation): newstring+=i print "The string without punctuation is",newstring  #SECOND METHOD word=raw_input("Enter string: ") punctuation='!?,.:;"\')(_-' newstring=word.translate(None,punctuation) print "The string without punctuation is",newstring   #Output for both methods Enter string: hello! welcome -to_python(programming.language)??, The string without punctuation is: hello welcome topythonprogramminglanguage 

with open('one.txt','r')as myFile:  str1=myFile.read()  print(str1)   punctuation = ['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'"]   for i in punctuation:  str1 = str1.replace(i," ")  myList=[] myList.extend(str1.split(" ")) print (str1)  for i in myList:  print(i,end='\n') print ("____________") 

왜 아무도 이것을 사용하지 않습니까?

 ''.join(filter(str.isalnum, s)) 

너무 느린?


Python을 사용하여 텍스트 파일에서 중지 단어를 제거하십시오.

print('====THIS IS HOW TO REMOVE STOP WORS====')  with open('one.txt','r')as myFile:  str1=myFile.read()  stop_words ="not", "is", "it", "By","between","This","By","A","when","And","up","Then","was","by","It","If","can","an","he","This","or","And","a","i","it","am","at","on","in","of","to","is","so","too","my","the","and","but","are","very","here","even","from","them","then","than","this","that","though","be","But","these"  myList=[]  myList.extend(str1.split(" "))  for i in myList:  if i not in stop_words:  print ("____________")  print(i,end='\n') 

문서를 대문자 또는 소문자로 변경하는 방법입니다.

print('@@@@This is lower case@@@@')  with open('students.txt','r')as myFile:  str1=myFile.read() str1.lower() print(str1.lower())  print('*****This is upper case****')  with open('students.txt','r')as myFile:  str1=myFile.read()  str1.upper()  print(str1.upper()) 

나는 다음과 같은 기능을 사용하고 싶다 :

def scrub(abc): while abc[-1] is in list(string.punctuation): abc=abc[:-1] while abc[0] is in list(string.punctuation): abc=abc[1:] return abc 

참고 URL :

https://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string



도움이 되겠다면 ↓↓↓ 배너 한번만 클릭 해주시면 감사합니다 ^^

반응형