문자열에서 구두점을 벗기는 가장 좋은 방법
-
06-07-2019 - |
문제
보다 간단한 방법이 있어야합니다.
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)
이것은 각 Char의 S.Replace보다 빠르지 만, 아래 타이밍에서 볼 수 있듯이 Regexes 또는 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)
위의 코드에서는 빈 문자열로 모든 비 영화 문자 ( w) 및 공백 ( s)을 대체합니다 (Re.Sub).
따라서 . 그리고 ? 구두점은 REGEX를 통해 S 변수를 실행 한 후 Variable '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({key: None for key in string.punctuation})
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
RE 가족에 더 익숙하다면 반드시 더 단순하지는 않지만 다른 방법입니다.
import re, string
s = "string. With. Punctuation?" # Sample string
out = re.sub('[%s]' % re.escape(string.punctuation), '', s)
파이썬 3 str
또는 파이썬 2 unicode
값, str.translate()
사전 만 필요합니다. CodePoints (정수)는 해당 매핑에서 조회하고 매핑 된 모든 것 None
제거됩니다.
(일부?) 구두점을 제거하려면 다음을 사용하십시오.
import string
remove_punct_map = dict.fromkeys(map(ord, string.punctuation))
s.translate(remove_punct_map)
그만큼 dict.fromkeys()
수업 방법 매핑을 만드는 것이 사소하게 만들고 모든 값을 None
키 순서를 기반으로합니다.
제거 모두 ASCII 구두점뿐만 아니라 문장 부호는 테이블이 조금 더 커야합니다. 보다 JF 세바스찬의 대답 (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{C}|\p{M}|\p{P}|\p{S}|\p{Z}]+', regex.UNICODE)
remove.sub(u" ", s).strip()
개인적으로, 나는 이것이 파이썬의 문자열에서 구두점을 제거하는 가장 좋은 방법이라고 생각합니다.
- 모든 유니 코드 구두점을 제거합니다
- 쉽게 수정할 수 있습니다. 예를 들어
\{S}
구두점을 제거하려면$
. - 예를 들어 보관하고 싶은 것과 제거하고 싶은 것에 대해 구체적으로 구체적으로 얻을 수 있습니다.
\{Pd}
대시 만 제거합니다. - 이 Regex는 또한 공백을 정규화합니다. 탭, 캐리지 리턴 및 기타 이상한 점을 멋진 단일 공간에 매핑합니다.
이것은 유니 코드 문자 속성을 사용합니다 Wikipedia에서 자세한 내용을 읽을 수 있습니다.
이것은 최상의 솔루션이 아닐 수도 있지만 이것이 내가 한 방식입니다.
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
Python 3.5의 한 라이너는 다음과 같습니다.
import string
"l*ots! o(f. p@u)n[c}t]u[a'ti\"on#$^?/".translate(str.maketrans({a:None for a in string.punctuation}))
아직이 답변을 보지 못했습니다. 정규식을 사용하십시오. 단어 문자 외에 모든 문자를 제거합니다 (\w
) 및 숫자 문자 (\d
), 그 다음에 공백 문자 (\s
):
import re
s = "string. With. Punctuation?" # Sample string
out = re.sub(ur'[^\w\d\s]+', '', s)
여기에 Regex가없는 해결책이 있습니다.
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 예제를 다시 작성하고 기능 내부 내부로 Regex 컴파일 단계를 이동하기 위해 변경했습니다. 여기서 내 생각은 모든 단계가 기능을 작동시키는 데 필요한 시간이 걸렸습니다. 아마도 당신은 분산 컴퓨팅을 사용하고 있으며 근로자들 사이에서 공유 할 수 없으며 re.compile
각 근로자를 밟습니다. 또한, 나는 Python 3에 대한 Maketran의 두 가지 다른 구현 시간에 궁금했습니다.
table = str.maketrans({key: None for key in string.punctuation})
vs
table = str.maketrans('', '', string.punctuation)
또한 반복 수를 줄이기 위해 교차로 기능을 활용하는 다른 방법을 사용하는 방법을 추가했습니다.
이것은 완전한 코드입니다.
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({key: None for key in string.punctuation})
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 ("____________")
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