Python – 정규식을 사용하여 텍스트의 패턴 대체

정규식(regex)은 패턴을 기반으로 하는 텍스트에서 필요한 정보를 추출하기 위한 것입니다. 또한 텍스트 전처리로 이어지는 패턴 기반 텍스트를 조작하는 데 널리 사용되며 다음과 같은 디지털 기술을 구현하는 데 매우 유용합니다. 자연어 처리(NLP) .

이 문서에서는 각 예가 그 자체로 고유한 시나리오인 여러 예를 제공하여 정규식을 사용하여 패턴을 대체하는 방법을 보여줍니다. 내용을 이해하는 것이 매우 필요합니다. re.sub()> 의 방법 re> (정규식) 모듈을 사용하여 주어진 솔루션을 이해합니다.

그만큼 re.sub()> 메소드는 주어진 문자열에 대해 전역 검색 및 전역 교체를 수행합니다. 문자열의 특정 패턴을 대체하는 데 사용됩니다. 이 함수에는 총 5개의 인수가 있습니다.

통사론: re.sub(패턴, repl, 문자열, 개수=0, 플래그=0)

매개변수:
패턴 – 검색하여 대체할 패턴
repl – 패턴을 교체할 문자열
string – 패턴이 저장되는 변수의 이름
count – 대체가 수행될 최대 문자 수
플래그 – 정규식 패턴의 의미를 수정하는 데 사용됩니다.

count> 그리고 flags> 선택적 인수입니다.

예시 1: 특정 텍스트 패턴 대체
이 예에서는 주어진 텍스트 패턴이 검색되어 문자열로 대체됩니다. 아이디어는 매우 일반적인 형식을 사용하는 것입니다. re.sub()> 처음 3개의 인수만 사용하는 메서드입니다.

아래는 구현입니다.




# Python implementation of substituting a> # specific text pattern in a string using regex> > # importing regex module> import> re> > # Function to perform> # operations on the strings> def> substitutor():> > > # a string variable> > sentence1> => 'It is raining outside.'> > > # replacing text 'raining' in the string> > # variable sentence1 with 'sunny' thus> > # passing first parameter as raining> > # second as sunny, third as the> > # variable name in which string is stored> > # and printing the modified string> > print> (re.sub(r> 'raining'> ,> 'sunny'> , sentence1))> > > # a string variable> > sentence2> => 'Thank you very very much.'> > > # replacing text 'very' in the string> > # variable sentence2 with 'so' thus> > # passing parameters at their> > # appropriate positions and printing> > # the modified string> > print> (re.sub(r> 'very'> ,> 'so'> , sentence2))> > # Driver Code:> substitutor()>

산출:

 It is sunny outside. Thank you so so much. 

문자열에 필요한 패턴이 몇 번이나 존재하더라도 re.sub()> 함수는 모든 것을 주어진 패턴으로 대체합니다. 이것이 바로 위의 예에서 'very'가 모두 'so'로 대체된 이유입니다.

예 2: 문자 세트를 특정 문자로 대체
임무는 문자 세트를 주어진 문자로 바꾸는 것입니다. 문자 세트는 문자 범위를 의미합니다. 에서 re.sub()> 메소드 문자 세트는 [ ](대괄호) 안에 작성됩니다.

이 예에서는 소문자 문자 집합(즉, [a-z])이 숫자 0으로 대체됩니다. 아래는 구현입니다.




# Python implementation of substituting> # a character set with a specific character> > # importing regex module> import> re> > # Function to perform> # operations on the strings> def> substitutor():> > > # a string variable> > sentence> => '22 April is celebrated as Earth Day.'> > > # replacing every lower case characters> > # in the variable sentence with 0 and> > # printing the modified string> > print> (re.sub(r> '[a-z]'> ,> '0'> , sentence))> > # Driver Code:> substitutor()>

산출:

 22 A0000 00 0000000000 00 E0000 D00. 

소문자와 대문자 문자 집합을 모두 대체해야 하는 경우 [a-zA-Z] 또는 다음과 같은 방식으로 대문자 문자 집합을 도입해야 합니다. 효과적인 방법은 플래그를 사용하는 것입니다.

예 3: 특정 문자로 문자 세트를 대소문자를 구분하지 않고 대체
이 예에서는 소문자와 대문자가 모두 지정된 문자로 대체됩니다. 의 사용으로 깃발 , 이 작업은 매우 쉽게 수행할 수 있습니다.

그만큼 re.I> 플래그는 re를 의미합니다. 무시 . 이 플래그를 re.sub()> 메소드를 사용하고 임의의 문자 세트(예: 소문자 또는 대문자)를 언급하면 ​​작업이 완료될 수 있습니다.

아래는 구현입니다.




# Python implementation of case-insensitive substitution> # of a character set with a specific character> > # importing regex module> import> re> > # Function to perform> # operations on the strings> def> substitutor():> > > # a string variable> > sentence> => '22 April is celebrated as Earth Day.'> > > # replacing both lowercase and> > # uppercase characters with 0 in> > # the variable sentence by using> > # flag and printing the modified string> > print> (re.sub(r> '[a-z]'> ,> '0'> , sentence, flags> => re.I))> > # Driver Code:> substitutor()>

산출:

 22 00000 00 0000000000 00 00000 000. 

예 4: 특정 문자 수까지 대체 수행
이 예에서 대체는 전체 문자열이 아닌 특정 문자 수까지 가능합니다. 이러한 유형의 대체를 수행하려면 re.sub()> 메소드에 인수가 있습니다 count> .

이 인수에 숫자 값을 제공하면 대체가 발생하는 문자 수를 제어할 수 있습니다. 아래는 구현입니다.




# Python implementation to perform substitution> # up to a certain number of characters> > # importing regex module> import> re> > # Function to perform> # operations on the strings> def> substitutor():> > > # a string variable> > sentence> => 'Follow your Passion.'> > > # case-insensitive substitution> > # on variable sentence upto> > # eight characters and printing> > # the modified string> > print> (re.sub(r> '[a-z]'> ,> '0'> , sentence,> 8> , flags> => re.I))> > # Driver Code:> substitutor()>

산출:

 000000 00ur Passion. 

예 5: 단축 문자 클래스를 사용한 대체 및 텍스트 전처리
Regex 모듈은 텍스트 전처리 중에 매우 일반적으로 사용되는 문자 집합에 대한 다양한 단축 문자 클래스를 제공합니다. 단축 문자 클래스를 사용하면 효율적인 코드를 작성할 수 있고 모든 문자 집합의 범위를 기억할 필요성이 줄어듭니다.

단축 문자 클래스에 대한 자세한 설명과 텍스트 전처리를 위해 Python에서 정규식을 작성하는 방법을 보려면 클릭하세요. 여기 . 다음은 일반적으로 사용되는 속기 문자 클래스 중 일부입니다.

w: 영숫자와 일치합니다.
W: @, #, ', +, %, –와 같은 영숫자가 아닌 문자와 일치합니다.
d: 숫자 문자와 일치
s: 공백 문자와 일치합니다.

일부 구문의 의미:
문자 클래스 또는 세트 뒤에 더하기(+) 기호 추가: 이전 문자 클래스 또는 세트를 적어도 1회 이상 반복합니다.

문자 클래스 또는 세트 뒤에 별표(*) 기호 추가: 이전 문자 클래스 또는 세트를 0회 이상 반복합니다.

문자 클래스 또는 세트 앞에 캐럿(^) 기호 추가: 일치하는 위치는 해당 문자 클래스에 대해 결정되거나 문자열의 시작 부분에 설정됩니다.

문자 클래스 또는 세트 뒤에 달러($) 기호 추가: 일치하는 위치는 해당 문자 클래스에 대해 결정되거나 문자열 끝에 설정됩니다.

이 예에서는 깨끗하고 오류 없는 문자열을 얻기 위해 텍스트 대체 및 전처리에 언급된 단축 문자 클래스를 사용하는 방법을 보여줍니다. 아래는 구현입니다.




# Python implementation of Substitution using> # shorthand character class and preprocessing of text> > # importing regex module> import> re> > # Function to perform> # operations on the strings> def> substitutor():> > > # list of strings> > S> => [> '2020 Olympic games have @# been cancelled'> ,> > 'Dr Vikram Sarabhai was +%--the ISRO’s first chairman'> ,> > 'Dr Abdul Kalam, the father of India's missile programme'> ]> > > # loop to iterate every element of list> > for> i> in> range> (> len> (S)):> > > # replacing every non-word character with a white space> > S[i]> => re.sub(r> 'W'> ,> ' '> , S[i])> > > # replacing every digit character with a white space> > S[i]> => re.sub(r> 'd'> ,> ' '> , S[i])> > > # replacing one or more white space with a single white space> > S[i]> => re.sub(r> 's+'> ,> ' '> , S[i])> > > # replacing alphabetic characters which have one or more> > # white space before and after them with a white space> > S[i]> => re.sub(r> 's+[a-z]s+'> ,> ' '> , S[i], flags> => re.I)> > > # substituting one or more white space which is at> > # beginning of the string with an empty string> > S[i]> => re.sub(r> '^s+'> , '', S[i])> > > # substituting one or more white space which is at> > # end of the string with an empty string> > S[i]> => re.sub(r> 's+$'> , '', S[i])> > > # loop to iterate every element of list> > for> i> in> range> (> len> (S)):> > > # printing each modified string> > print> (S[i])> > # Driver Code:> substitutor()>

산출:

 Olympic games have been cancelled Dr Vikram Sarabhai was the ISRO first chairman Dr Abdul Kalam the father of India missile programme