Python에서 AWS Amazon Translate를 사용하여 Twitter API v2에서 트윗 번역

연구원은 Twitter API를 사용하여 다양한 연구 연구를 위한 Twitter 데이터를 얻습니다. 경우에 따라 트윗 텍스트를 한 언어에서 다른 언어로 번역한 다음 텍스트에 대한 추가 분석을 수행하려고 합니다.

이 게시물에서는 Twitter API v2를 사용하여 트윗을 가져온 다음 Python에서 Amazon Translate를 사용하여 한 언어에서 다른 언어로 트윗을 변환하는 방법을 알아봅니다.

전제 조건



이 자습서를 따르려면 . 개발자 계정이 있으면 트윗을 가져오기 위해 Twitter API v2에 연결하기 위한 전달자 토큰이 필요합니다. 무기명 토큰을 얻기 위해.

Amazon Translate 서비스를 사용하려면 Amazon Web Services(AWS) 계정도 필요합니다. AWS 자격 증명을 로컬로 설정하는 방법에 대한 지침은 here 에서 찾을 수 있습니다. 샘플 코드가 작동하도록 설정하십시오.


Twitter API v2에 연결하기 위해 twarc library을 사용합니다. Amazon Translate를 사용하려면 boto3 library을 사용합니다. 따라서 먼저 필요한 라이브러리를 가져옵니다.

from twarc import Twarc2, expansions
import boto3


다음으로 Twitter API v2에서 트윗을 가져오는 데 사용할 twarc 클라이언트를 설정합니다. 이를 설정하기 위해 베어러 토큰(전제 조건 섹션에서 얻음)을 전달합니다.

# Replace your bearer token below
client = Twarc2(bearer_token="REPLACE_ME")


그런 다음 입력 트윗 텍스트, 소스 언어(트윗이 있는 언어) 및 대상 언어(트윗을 번역할 언어)를 받는 작은 도우미 함수를 작성합니다. 이 함수에서는 boto3.client("translate") 를 작성하여 Amazon Translate 클라이언트를 초기화합니다.

클라이언트가 설정되면 트윗 텍스트, 소스 언어 및 대상 언어를 전달합니다. 응답을 받으면 이 함수의 원본 텍스트, 번역된 텍스트, 소스 및 대상 언어 코드에 대한 적절한 값이 포함된 사전을 반환합니다.

def translate(input_text, source_lang, target_lang):

    translate_client = boto3.client("translate")

    result = translate_client.translate_text(Text=input_text, SourceLanguageCode=source_lang,
                                             TargetLanguageCode=target_lang)

    return {"originalText": input_text, "translatedText": result.get('TranslatedText'),
            "sourceLang": result.get('SourceLanguageCode'), "targetLang": result.get('TargetLanguageCode')}


그런 다음 기본 기능을 지정합니다. 이 함수에서는 twarc 라이브러리의 search_recent 메서드를 호출하고 검색 쿼리를 전달합니다. 검색어에 지정된 조건에 따라 지난 7일 동안의 트윗을 검색합니다.

이 데모에서는 힌디어( from:SentimentsDev )로 된 특정 계정( lang:hi )의 트윗을 원한다고 지정합니다. 검색어 작성에 대해 자세히 알아보세요.

def main():

    # Replace the query below with your own
    query = "from:SentimentsDev lang:hi -is:retweet"

    # The search_all method call the recent-archive search endpoint to get Tweets based on the query
    search_results = client.search_recent(query=query, max_results=100)

    # Twarc returns all Tweets for the criteria set above, so we page through the results
    for page in search_results:
        # The Twitter API v2 returns the Tweet information and the user, media etc.  separately
        # so we use expansions.flatten to get all the information in a single JSON
        result = expansions.flatten(page)
        for tweet in result:
            # Here we are calling the translate function and passing it the tweet text, the source language code
            # and the target language code
            response = translate(tweet['text'], tweet['lang'], 'en')
            # Below we print the original text, the translated text, the source and target language codes
            print("Original Text: {}".format(response['originalText']))
            print("Translated Text: {}".format(response['translatedText']))
            print("Source Language: {}".format(response['sourceLang']))
            print("Target Language: {}".format(response['targetLang']))


마지막으로 메인 함수를 호출합니다.

if __name__ == "__main__":
    main()


이 예에서 트윗은 다음과 같습니다.



따라서 응답은 다음과 같습니다.

Original Text: आज का मौसम बहुत अच्छा है
Translated Text: Today's weather is very good
Source Language: hi
Target Language: en


보시다시피 원본 트윗은 힌디어(언어 코드hi로 표시됨)로 되어 있었고 영어로 변환되었습니다. 마찬가지로 Amazon Translate를 사용하여 다양한 다른 언어 간에 번역할 수 있습니다.

이 작은 튜토리얼이 도움이 되었기를 바랍니다. 질문이나 피드백이 있으면 Twitter에서 저에게 연락해 주세요.

좋은 웹페이지 즐겨찾기