웹사이트 검색

Python – 정규 표현식을 사용하여 'g' 뒤에 하나 이상의 e가 포함된 단어를 일치시키는 프로그램


Python은 데이터 시각화 및 딥 러닝 분야에서 작동하는 가장 강력한 프로그래밍 언어입니다. 정규식이라고도 알려진 정규식은 특정 문서에서 문자나 텍스트를 검색하는 효과적인 도구입니다. Python 언어는 사용자에게 기본 계산부터 복잡한 계산까지 다양한 역할을 제공합니다. Python 메서드는 다양한 기능을 사용하여 주어진 텍스트의 단어를 일치시킵니다. Python은 개발자가 가장 선호하는 고급 프로그래밍이자 다목적 프로그래밍이며 데이터 분석에도 널리 사용됩니다.

정규식을 사용하여 단어를 일치시키는 프로그램

이를 설명하기 위해 특정 값을 갖는 text라는 변수를 사용하는 것과 같은 예를 들 수 있습니다.

Text="John은 축구 경기에 천재입니다."

출력은 [genius, game]으로 인쇄됩니다.

정규식

  • 문자열 시작 부분의 'r'은 패턴을 컴파일할 때 특수 문자가 이스케이프되지 않도록 원시 입력으로 처리되어야 함을 나타냅니다.

  • `\b` 문자는 문자 없이 앞에 `"g"가 붙은 완전한 단어만 찾을 수 있도록 단어 경계를 정의합니다.

  • 둘 이상의 연속된 e-문자가 존재할 수 있는 공백에 나타나는 각 g-단어는 그 뒤에 제공된 다른 경계 \b 문자로 끝나야 합니다. 명확한 단어 패턴 사이에 캡처된 다른 모든 반복(하나의 OK- Zeroth 포함) 전자 문자는 사전에 계산되어 이후 일치 개체 format_list 데이터 유형에 저장된 일치하는 구문만 반환합니다.

접근하다:-

  • 접근법 1 - findall() 함수 사용

  • 접근 방식 2 - 일치 기능 사용

  • 접근법 3 - finditer() 함수 사용

접근법 1: findall() 함수의 도움으로 정규식을 사용하여 단어를 일치시키는 Python 프로그램

문장은 일련의 단어로 초기화되며 'g'로 시작하고 뒤에 하나 이상의 e가 오는 단어는 findall 메소드를 사용하여 찾을 수 있습니다.

연산

  • 1단계 − 정규식 값을 사용하기 위해 "re" 모듈을 가져옵니다.

  • 2단계 − 정규식은 "pattern"이라는 변수에 저장됩니다.

  • 3단계 − findall() 함수는 정규식을 사용하여 패턴과 문장이라는 두 개의 매개변수로 정의됩니다.

  • 4단계 − 마지막으로 명세서가 인쇄됩니다.

예

#importing the re module
import re
#the input is initialized with a word starting with g and followed by one or two e’s
sentence = "geetanjali, gear, gemma, hello"
#Initializing the variable to store the value
pattern = r'\bg\w*e+\w*\b'
#Using the findall function, to match the pattern with the sentence
matching = re.findall(pattern, sentence)
#The list is returned with the string values
print("Words which are matching from the input:",matching)

산출

Words which are matching from the input: ['geetanjali', 'gear', 'gemma']

접근법 2: match() 함수의 도움으로 정규식을 사용하여 단어를 일치시키는 Python 프로그램

주어진 문장에서 해당 단어를 모두 찾는 데 사용되는 메서드는 match() 메서드입니다.

연산

  • 1단계 - 정규 표현식을 사용하는 데 필요한 모듈을 가져옵니다.

  • 2단계 − 함수는 두 개의 매개변수로 정의됩니다.

  • 3단계 − 일치하는 항목이 없으면 빈 목록을 반환합니다.

  • 4단계 - 최종 목록이 인쇄됩니다.

예

#importing the re module
import re
#the input is initialized with word starting with g and followed by one or two e’s
sentence = "geetanjali, gear, gemma, hello"
#Initializing the variable to store the value
pattern = r'\bg\w*e+\w*\b'
#function is defined with two parameters
def matchword(pattern, sentence):
    if not sentence:
        return []
    match = re.match(pattern, sentence)
    if match:
        return [match.group()] + matchword(pattern, sentence[match.end():])
    else:
        return matchword(pattern, sentence[1:])

matching = matchword(pattern, sentence)
#The list is returned with the string values
print("Words which are matching from the input:",matching)

산출

Words which are matching from the input: ['geetanjali', 'gear', 'gemma']

접근법 3: finditer() 함수의 도움으로 정규식을 사용하여 단어를 일치시키는 Python 프로그램

findall 메소드와 비교하여 finditer()는 'g'로 시작하고 뒤에 하나 또는 두 개의 e가 오는 주어진 문장에서 모든 일치 항목을 인쇄하는 데 사용됩니다.

연산

  • 1단계 − 정규식 값을 사용하기 위해 필수 "re" 모듈을 가져옵니다.

  • 2단계 - 입력이 초기화되고 다양한 단어로 구성됩니다.

  • 3단계 − 정규식은 "pattern"이라는 변수에 저장됩니다.

  • 4단계 − findall() 함수는 정규 표현식을 사용하여 패턴과 문장이라는 두 개의 매개변수로 정의됩니다.

  • 5단계 − 마지막으로 명세서가 인쇄됩니다.

예

#importing the re module
import re
#the input is initialized with a word starting with g and followed by one or two e’s
sentence = "geek, gear, gemma, hello"
#Initializing the variable to store the value
pattern = r'\bg\w*e+\w*\b'
#Using the finditer function, to match the pattern with the sentence
matches = re.finditer(pattern, sentence)
#for loop is used to iterate through the sentence
for match in matches:
    print(match.group())

산출

geek
gear
gemma

결론

정규식의 일반적인 용도 중 하나는 "g" 뒤에 하나 이상의 e가 오는 것과 같이 특정 문자 시퀀스가 포함된 단어를 검색하는 것입니다. 이 패턴은 Python과 내장 정규식 모듈을 사용하여 쉽게 일치시킬 수 있습니다. 단어의 발생을 일치시키는 다양한 접근 방식이 다양한 방법을 사용하여 설명됩니다.

관련기사: