【问题标题】:Google Translate API - detect language + translate document (xlsx, csv)Google Translate API - 检测语言 + 翻译文档(xlsx、csv)
【发布时间】:2021-10-03 11:39:42
【问题描述】:

我正在尝试使用 Google Cloud Translation API 翻译包含多种语言文本的 excel(或 csv)文档,而我的目标语言是英语。

我想使用“批量翻译文本(仅限高级版)”代码示例(此处链接:https://cloud.google.com/translate/docs/samples/translate-v3-batch-translate-text)但代码示例中有一行定义源语言,因此只能有一种源语言.

但我需要先检测文档中的语言,然后将文本翻译成英文。有用于检测文本“检测语言(高级)”(链接:https://cloud.google.com/translate/docs/advanced/detecting-language-v3)的简单字符串中的语言的代码示例,但我需要将第一个翻译文档的代码示例(但只定义了一种源语言)与检测语言而不是定义一种源语言的能力。

资源中有这种类型的代码示例吗?怎么解决?

这里是有问题的示例代码:

from google.cloud import translate


def batch_translate_text(
    input_uri="gs://YOUR_BUCKET_ID/path/to/your/file.txt",
    output_uri="gs://YOUR_BUCKET_ID/path/to/save/results/",
    project_id="YOUR_PROJECT_ID",
    timeout=180,
):
    """Translates a batch of texts on GCS and stores the result in a GCS location."""

    client = translate.TranslationServiceClient()

    location = "us-central1"
    # Supported file types: https://cloud.google.com/translate/docs/supported-formats
    gcs_source = {"input_uri": input_uri}

    input_configs_element = {
        "gcs_source": gcs_source,
        "mime_type": "text/plain",  # Can be "text/plain" or "text/html".
    }
    gcs_destination = {"output_uri_prefix": output_uri}
    output_config = {"gcs_destination": gcs_destination}
    parent = f"projects/{project_id}/locations/{location}"

    # Supported language codes: https://cloud.google.com/translate/docs/language
    operation = client.batch_translate_text(
        request={
            "parent": parent,
            "source_language_code": "en",
            "target_language_codes": ["ja"],  # Up to 10 language codes here.
            "input_configs": [input_configs_element],
            "output_config": output_config,
        }
    )

    print("Waiting for operation to complete...")
    response = operation.result(timeout)

    print("Total Characters: {}".format(response.total_characters))
    print("Translated Characters: {}".format(response.translated_characters))

【问题讨论】:

    标签: python google-cloud-platform translation google-translate google-translation-api


    【解决方案1】:

    不幸的是,无法使用batchTranslateText 将值数组传递给字段source_language_code。我可以建议每个文件执行detectLanguagetranslateText

    以下代码的作用是:

    1. 它提取要翻译的内容。出于测试目的,使用的 csv 文件只有 1 列,sample1.csv 的内容位于 tl(他加禄语)中,而 sample2.csv 位于 es(西班牙语)中。
    2. 将提取的内容传递给detect_language()以获取检测到的语言代码。
    3. 将所有必需的参数传递给translate_text()进行翻译

    注意:下面的代码仅使用一列的 csv 文件进行测试。编辑main() 处的代码以在您要提取数据的列上进行模式化。

    from google.cloud import translate
    import csv
    
    
    def listToString(s):
        """ Transform list to string"""
        str1 = " "
        return (str1.join(s))
    
    def detect_language(project_id,content):
        """Detecting the language of a text string."""
    
        client = translate.TranslationServiceClient()
        location = "global"
        parent = f"projects/{project_id}/locations/{location}"
    
        response = client.detect_language(
            content=content,
            parent=parent,
            mime_type="text/plain",  # mime types: text/plain, text/html
        )
    
        for language in response.languages:
            return language.language_code
    
    
    def translate_text(text, project_id,source_lang):
        """Translating Text."""
    
        client = translate.TranslationServiceClient()
        location = "global"
        parent = f"projects/{project_id}/locations/{location}"
    
        # Detail on supported types can be found here:
        # https://cloud.google.com/translate/docs/supported-formats
        response = client.translate_text(
            request={
                "parent": parent,
                "contents": [text],
                "mime_type": "text/plain",  # mime types: text/plain, text/html
                "source_language_code": source_lang,
                "target_language_code": "en-US",
            }
        )
    
        # Display the translation for each input text provided
        for translation in response.translations:
            print("Translated text: {}".format(translation.translated_text))
            
    def main():
    
        project_id="your-project-id"
        csv_files = ["sample1.csv","sample2.csv"]
        # Perform your content extraction here if you have a different file format #
        for csv_file in csv_files:
            csv_file = open(csv_file)
            read_csv = csv.reader(csv_file)
            content_csv = []
    
            for row in read_csv:
                content_csv.extend(row)
            content = listToString(content_csv) # convert list to string
            detect = detect_language(project_id=project_id,content=content)
            translate_text(text=content,project_id=project_id,source_lang=detect)
    
    if __name__ == "__main__":
        main()
    

    sample1.csv:

    kamusta
    ayos
    

    sample2.csv:

    cómo estás
    okey
    

    使用上面的代码输出:

    Translated text: how are you okay
    Translated text: how are you ok
    

    【讨论】:

    • 1/2 非常感谢您的回答 Ricco D。我尝试使用示例文件运行它并收到错误消息:“FileNotFoundError: [Errno 2] No such file or directory "(第 57 行和第 69 行)我的文件位于谷歌云平台的云存储(存储桶)中,并且我在单独的存储桶中有一个用于导出文件的空文件夹。我还尝试将 project_id="your-project-id" 处的“your-project-id”替换为我的项目 ID 的实际名称,并且也仅使用“project-id”作为项目 ID 在我的 json 文件中定义我'如果可能,我想再问两个问题(在 2/2 中继续)
    • 2/2 1) 是否可以将“导入 csv”与我的 csv 文件源位置的路径交换 (input_uri="gs://YOUR_BUCKET_ID/path/to/your/file .txt") 并定义新翻译文件的导出位置? ( output_uri="gs://YOUR_BUCKET_ID/path/to/save/results/") 2) 您在注释中提到“以下代码仅使用一列的 csv 文件进行测试。将 main() 中的代码编辑为您要提取数据的列上的模式。”如果有(例如)10 列和 10 行的 csv 文件,我应该如何在 main() 编辑代码?谢谢!
    • 我为此提要创建了一个关于读取和写入云存储的更新问题:stackoverflow.com/questions/68565106/…
    • 1.) 您从创建的问题 stackoverflow.com/questions/68565106/… 中得到了很好的答案。 2.) 这很难回答,因为这取决于您希望如何解析数据。您想将所有 10 行和 10 列组合成 1 个字符串吗?你想每行组合字符串吗?每列?也有多种方法可以做到这一点。我可以为您建议的是确定您的要求并通读如何解析 CSV 文件。喜欢这篇文章realpython.com/python-csv
    • 当您确定解析 CSV 文件的目标并为其提供代码后,您可以发布一个新问题,社区将很乐意提供帮助! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    • 2015-07-25
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    • 2014-04-21
    相关资源
    最近更新 更多