Programming

파이썬에서 여러 분리 문자로 문자열 분리하기

procodes 2020. 2. 19. 22:16
반응형

파이썬에서 여러 분리 문자로 문자열 분리하기


이 질문에는 이미 답변이 있습니다.

온라인에서 일부 답변을 찾았지만 정규 표현식에 대한 경험이 없으므로 여기에 필요한 것이 있다고 생각합니다.

';'에 의해 분리되어야하는 문자열이 있습니다. 또는 ','즉, 세미콜론 또는 쉼표 뒤에 공백이 있어야합니다. 후행 공백이없는 개별 쉼표는 그대로 두어야합니다.

문자열 예 :

"b-staged divinylsiloxane-bis-benzocyclobutene [124221-30-3], mesitylene [000108-67-8]; polymerized 1,2-dihydro-2,2,4- trimethyl quinoline [026780-96-1]"

다음을 포함하는 목록으로 분할해야합니다.

('b-staged divinylsiloxane-bis-benzocyclobutene [124221-30-3]' , 'mesitylene [000108-67-8]', 'polymerized 1,2-dihydro-2,2,4- trimethyl quinoline [026780-96-1]') 

운 좋게도 파이썬에는이 내장 기능이 있습니다 :)

import re
re.split('; |, ',str)

업데이트 :
귀하의 의견에 따라 :

>>> a='Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n',a)
['Beautiful', 'is', 'better', 'than', 'ugly']

수행합니다 str.replace('; ', ', ')다음str.split(', ')


다음은 정규 표현식을 사용하여 반복 가능한 구분 기호에 대한 안전한 방법입니다.

>>> import re
>>> delimiters = "a", "...", "(c)"
>>> example = "stackoverflow (c) is awesome... isn't it?"
>>> regexPattern = '|'.join(map(re.escape, delimiters))
>>> regexPattern
'a|\\.\\.\\.|\\(c\\)'
>>> re.split(regexPattern, example)
['st', 'ckoverflow ', ' is ', 'wesome', " isn't it?"]

re.escape 를 사용하면 패턴을 자동으로 빌드하고 구분 기호를 멋지게 이스케이프 할 수 있습니다.

이 솔루션은 다음과 같은 복사 붙여 넣기 기능을 제공합니다.

def split(delimiters, string, maxsplit=0):
    import re
    regexPattern = '|'.join(map(re.escape, delimiters))
    return re.split(regexPattern, string, maxsplit)

동일한 구분자를 사용하여 자주 분할하려는 경우 description과 use처럼 미리 정규식을 컴파일하십시오 RegexObject.split.


위의 Jonathan의 대답에 따라 이것은 특정 구분 기호에서만 작동하는 것으로 보입니다. 예를 들면 다음과 같습니다.

>>> a='Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n',a)
['Beautiful', 'is', 'better', 'than', 'ugly']

>>> b='1999-05-03 10:37:00'
>>> re.split('- :', b)
['1999-05-03 10:37:00']

구분 기호를 대괄호 안에 넣으면 더 효과적으로 작동하는 것 같습니다.

>>> re.split('[- :]', b)
['1999', '05', '03', '10', '37', '00']

정규식은 다음과 같습니다.

import re
# "semicolon or (a comma followed by a space)"
pattern = re.compile(r";|, ")

# "(semicolon or a comma) followed by a space"
pattern = re.compile(r"[;,] ")

print pattern.split(text)

참고 URL : https://stackoverflow.com/questions/4998629/split-string-with-multiple-delimiters-in-python



반응형