二創:https://mxuannc.me/

原文:https://www.facebook.com/YuanYuanZi/posts/pfbid02J2ftxZGWs9ZroLKKKm8ygPz5QAi9N9fU2yKxSumZZhwbVd1KRWPHsJE7dh5SG1uil?__cft__[0]=AZVaZEtPvAPMh1KoHZ3egpQKJmZzeZCjzQe_yvgFkjc6Ds03pfo01G-aWqv0jP5kET6kW4UcalM-Ff5OeMAlNqZ1OinURABcjzRaauBYNKA1nmms-gZEs1EGs-4JjaeqJsF_9z6U-noa7hoYYkIX5A9y3dCgoSYYi5NpdxEVL1UGSA&__tn__=%2CO%2CP-R

如何申請openAI API金鑰:https://hackmd.io/@flagmaker/BJuxF7bkye

第一次用的話,可能要在電腦內建的cmd裡面先跑過pip install XXX(各種等等python要import的東西,我沒學過程式所以我也講不清楚。總之各位如果python出現error,可以直接整段複製丟chatGPT問他怎麼辦xd)

以下是要貼上python的東東,openAI API金鑰跟長文文本記得改成你自己的內容。

import openai
import os
from docx import Document
from docx.shared import Pt

# 在這裡輸入你的 OpenAI API 金鑰
api_key = '**在這邊貼上!!!!!**'
def translate_segment(segment, model="gpt-3.5-turbo-1106"):
    try:
        # 使用新版 API,並直接傳遞 api_key
        client = openai.OpenAI(api_key=api_key)  # 初始化 client 並傳遞 API 金鑰
        response = client.chat.completions.create(
            model=model,
            messages=[ 
                {"role": "system", "content": "You are a professional book translator. Please translate the following English text to Traditional Chinese without adding any extra content or summary."},
                {"role": "user", "content": f"Translate the following English text to Traditional Chinese:\\n\\n{segment}"}
            ]
        )
        return response.choices[0].message.content
    except Exception as e:
        print("Error during translation:", e)
        return None

def split_text_smart(text, max_length=600):
    sentences = text.split('. ')
    current_chunk = ""
    chunks = []
    for sentence in sentences:
        if len(current_chunk) + len(sentence) < max_length:
            current_chunk += sentence + '. '
        else:
            chunks.append(current_chunk.strip())
            current_chunk = sentence + '. '
    if current_chunk:
        chunks.append(current_chunk.strip())
    return chunks

def clean_text(text):
    # 這裡可以加入更多文本整理的邏輯,比如移除多餘的空格或標點
    text = text.strip()  # 移除前後空格
    text = ' '.join(text.split())  # 移除多餘的空白字元
    return text
# 你的長文本在這裡
long_text = '''
**在這邊貼上文本!!!!!!!!!**
'''
# 整理文本
cleaned_text = clean_text(long_text)

# 分割長文本
segments = split_text_smart(cleaned_text)

# 翻譯每個分割的段落
translated_segments = []
for segment in segments:
    translated = translate_segment(segment)
    if translated:
        translated_segments.append(translated)

# 組合翻譯後的文本
translated_text = "\\n".join(translated_segments)
print(translated_text)

# 創建 Word 文件
doc = Document()
doc.add_heading('Translated Text', 0)

# 添加翻譯內容到 Word 文件
for translated_segment in translated_segments:
    # 每段翻譯結果保持為一個段落
    doc.add_paragraph(translated_segment)

# 儲存文件
file_path = 'translated_text.docx'
doc.save(file_path)

# 查看當前工作目錄
current_directory = os.getcwd()
print(f"當前工作目錄是: {current_directory}")