파이썬으로 텍스트에서 사용자 이름 추출하기

PythonBeginner
지금 연습하기

소개

이 프로젝트에서는 Python 을 사용하여 텍스트에서 사용자 이름을 추출하는 방법을 배우게 됩니다. 이는 소셜 미디어 및 인스턴트 메시징 애플리케이션에서 흔히 사용되는 작업으로, 여기서 @ 문자는 종종 누군가를 언급하는 데 사용됩니다.

👀 미리보기

## Example 1
>>> from parse_username import after_at
>>> text = "@LabEx @labex I won in the @ competition"
>>> print(after_at(text))
['LabEx', 'labex']
## Example 2
>>> text = "@LabEx@labex I won in the @ competition"
>>> print(after_at(text))
['LabEx', 'labex']
## Example 3
>>> text = "@labex @LabEx I won in the @LabEx competition"
>>> print(after_at(text))
['LabEx', 'labex']
## Example 4
>>> text = "@!LabEx @labex I won in the competition"
>>> print(after_at(text))
['labex']
## Example 5
>>> text = "I won in the competition@"
>>> print(after_at(text))
[]
## Example 6
>>> text = "LabEx@!"
>>> print(after_at(text))
[]
## Example 7
>>> text = "@!@LabEx @labex I won in the @LabEx competition @experiment"
>>> print(after_at(text))
['LabEx', 'experiment', 'labex']

🎯 과제

이 프로젝트에서는 다음을 배우게 됩니다.

  • 주어진 텍스트에서 사용자 이름을 추출하기 위해 after_at 함수를 구현하는 방법
  • 엣지 케이스를 처리하고 함수의 성능을 최적화하는 방법
  • 다양한 입력 시나리오로 함수를 테스트하는 방법

🏆 성과

이 프로젝트를 완료하면 다음을 수행할 수 있습니다.

  • Python 을 사용하여 텍스트에서 관련 정보를 파싱하고 추출하는 방법을 이해합니다.
  • 텍스트에서 사용자 이름을 추출하는 강력하고 효율적인 함수를 개발합니다.
  • 문제 해결 능력을 적용하여 함수의 기능을 향상시킵니다.
  • 예상대로 작동하는지 확인하기 위해 코드를 철저하게 테스트합니다.

after_at 함수 구현

이 단계에서는 주어진 텍스트에서 사용자 이름을 추출하는 after_at 함수를 구현합니다.

  1. 코드 편집기에서 parse_username.py 파일을 엽니다.

  2. after_at 함수 정의를 찾습니다.

  3. 함수는 문자열 text를 입력으로 받으며, 비어 있을 수도 있습니다.

  4. 함수 내부에서 추출된 사용자 이름을 저장하기 위해 usernames라는 빈 리스트를 초기화합니다.

  5. find() 메서드를 사용하여 text에서 @ 문자가 처음 나타나는 인덱스를 찾고, 이를 at_index 변수에 저장합니다.

  6. at_index-1이 아닌 동안 (즉, @ 문자가 발견된 경우):

    • username이라는 빈 문자열을 초기화합니다.
    • @ 문자 다음 인덱스부터 시작하여 text 문자열의 문자를 반복합니다.
    • 각 문자에 대해 isalnum()isalpha() 메서드를 사용하여 영숫자 또는 밑줄인지 확인합니다.
    • 문자가 유효하면 username 문자열에 추가합니다.
    • 문자가 유효하지 않으면 루프를 종료합니다.
    • username이 비어 있지 않으면 usernames 리스트에 추가합니다.
    • 이전 @ 문자 다음 인덱스부터 시작하여 text 문자열에서 @ 문자가 다음으로 나타나는 위치를 찾습니다.
  7. 루프가 끝난 후, set() 함수를 사용하여 usernames 리스트에서 중복된 사용자 이름을 제거합니다.

  8. 사용자 이름의 각 발생 횟수를 기준으로 사용자 정의 키 함수와 함께 sorted() 함수를 사용하여 usernames 리스트를 내림차순으로 정렬합니다.

  9. 정렬된 usernames 리스트를 반환합니다.

완성된 after_at 함수는 다음과 같아야 합니다.

def after_at(text):
    usernames = []
    at_index = text.find("@")  ## Find the index of the first occurrence of "@"
    while at_index != -1:  ## Continue loop until no more "@" symbols are found
        username = ""
        for char in text[
            at_index + 1 :
        ]:  ## Iterate over the characters after the "@" symbol
            if (
                char.isalnum() or char == "_" or char.isalpha()
            ):  ## Check if the character is alphanumeric or underscore
                username += char  ## Add the character to the username
            else:
                break  ## If the character is not alphanumeric or underscore, stop adding characters to the username
        if username:
            usernames.append(username)  ## Add the extracted username to the list
        at_index = text.find(
            "@", at_index + 1
        )  ## Find the next "@" symbol starting from the next index

    ## Remove duplicates and sort by occurrence count in descending order
    usernames = sorted(
        list(set(usernames)), key=lambda x: usernames.count(x), reverse=True
    )

    return usernames
✨ 솔루션 확인 및 연습

after_at 함수 테스트

이 단계에서는 제공된 예제를 사용하여 after_at 함수를 테스트합니다.

  1. 코드 편집기에서 parse_username.py 파일을 엽니다.
  2. 파일 하단에서 if __name__ == "__main__": 블록을 찾습니다.
  3. 블록 내부에 다음 코드를 추가하여 after_at 함수를 테스트합니다.
## Example 1
print(after_at("@LabEx @labex I won in the @ competition"))
## Example 2
print(after_at("@LabEx@labex I won in the @ competition"))
## Example 3
print(after_at("@labex @LabEx I won in the @LabEx competition"))
## Example 4
print(after_at("@!LabEx @labex I won in the competition"))
## Example 5
print(after_at("I won in the competition@"))
## Example 6
print(after_at("LabEx@!"))
## Example 7
print(after_at("@!@LabEx @labex I won in the @LabEx competition @experiment"))
  1. parse_username.py 파일을 저장합니다.
  2. 다음 명령을 사용하여 터미널 또는 명령 프롬프트에서 parse_username.py 파일을 실행합니다.
python parse_username.py
  1. 출력이 챌린지에서 제공된 예상 결과와 일치하는지 확인합니다.
['LabEx', 'labex']
['LabEx', 'labex']
['LabEx', 'labex']
['labex']
[]
[]
['LabEx', 'experiment', 'labex']
✨ 솔루션 확인 및 연습

요약

축하합니다! 이 프로젝트를 완료했습니다. LabEx 에서 더 많은 랩을 연습하여 기술을 향상시킬 수 있습니다.