Created
January 19, 2024 16:30
-
-
Save l1fe/b55164e55e25c4706a20ae80ed8267c2 to your computer and use it in GitHub Desktop.
Translate CSV Table Column with DeepL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import requests | |
| import pandas as pd | |
| def translate_text(text, target_language, api_key): | |
| url = "https://api.deepl.com/v2/translate" | |
| params = { | |
| "auth_key": api_key, | |
| "text": text, | |
| "target_lang": target_language | |
| } | |
| response = requests.get(url, params=params) | |
| if response.status_code == 200: | |
| return response.json()['translations'][0]['text'] | |
| else: | |
| # Error handling | |
| print(f"Error in translation API: {response.status_code} - {response.text}") | |
| return text | |
| def translate_csv(input_csv_path, output_csv_path, target_language, api_key): | |
| df = pd.read_csv(input_csv_path) | |
| # Translate only the 'title' column | |
| df['translated_title'] = df['title'].apply(lambda text: translate_text(text, target_language, api_key) if pd.notnull(text) else text) | |
| # Write to new CSV, preserving format | |
| df.to_csv(output_csv_path, index=False) | |
| api_key = "" # Replace with your DeepL API key | |
| input_csv_path = "input.csv" # Path to your input CSV | |
| output_csv_path = "output.csv" # Path for the translated CSV | |
| target_language = "DE" # Target language code (e.g., "DE" for German) | |
| translate_csv(input_csv_path, output_csv_path, target_language, api_key) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment