巧用Python實(shí)現(xiàn)自動(dòng)化翻譯任務(wù)分配詳解
一、場景再現(xiàn)
小張是翻譯公司的一名項(xiàng)目經(jīng)理,他需要經(jīng)常向譯員分配翻譯任務(wù),管理項(xiàng)目進(jìn)度。在沒有購買服務(wù)器版或在線翻譯CAT工具輔助的前提下,他把10萬字的項(xiàng)目文檔快速分配給10名譯員。整個(gè)過程中,他要手動(dòng)計(jì)算字?jǐn)?shù)、切分文件、核對名單、發(fā)送郵件,檢查是否發(fā)送成功。這些繁瑣的工作一般會(huì)花費(fèi)他一二個(gè)小時(shí)的時(shí)間。更糟糕的是,手工操作時(shí)常出錯(cuò),比如:同一個(gè)翻譯任務(wù)誤發(fā)給兩名譯員,而另一個(gè)翻譯任務(wù)卻無人認(rèn)領(lǐng);手工等額分配翻譯任務(wù)時(shí)速度慢而且不夠準(zhǔn)確,直接影響到項(xiàng)目經(jīng)理的專業(yè)形象和翻譯項(xiàng)目進(jìn)度。
事實(shí)上,小張面臨的并非個(gè)性問題,翻譯項(xiàng)目管理中這是一項(xiàng)常規(guī)的操作。如果有YiCAT或譯馬在線CAT工具,可以實(shí)現(xiàn)線上任務(wù)的快速分配,還可以保留原有文本格式。但是在預(yù)算有限的情況下,人工進(jìn)行任務(wù)分配,就有可能面臨下面的問題:
字?jǐn)?shù)統(tǒng)計(jì)不精確:Word自帶的字?jǐn)?shù)統(tǒng)計(jì)與翻譯行業(yè)標(biāo)準(zhǔn)存在差異
文件切分不準(zhǔn)確:手動(dòng)切分難以保證每份文件的詞數(shù)或字?jǐn)?shù)相等
郵件發(fā)送效率低:重復(fù)的復(fù)制粘貼、附件添加消耗大量時(shí)間
人工錯(cuò)誤難以避免:人工操作難免出現(xiàn)分配錯(cuò)誤或遺漏
二、技術(shù)分析
為解決以上痛點(diǎn),提升翻譯任務(wù)分配效率,根據(jù)翻譯任務(wù)的分配流程,我們決定借助大語言模型DeepSeek編寫Python代碼,打造一款翻譯項(xiàng)目的智能分派系統(tǒng),批量完成任務(wù)的按單詞切分、任務(wù)數(shù)量核對、批量發(fā)送翻譯任務(wù),整體框架設(shè)計(jì)如下:
原始文檔 → 智能切分文檔 → 譯員名單匹配 → 批量發(fā)送 → 結(jié)果反饋
以上流程中,將翻譯任務(wù)分派進(jìn)行自動(dòng)化操作,減少人工干預(yù)環(huán)節(jié),并在關(guān)鍵環(huán)節(jié)設(shè)置檢查點(diǎn),以便得到精準(zhǔn)的報(bào)錯(cuò)信息。本系統(tǒng)操作簡單,錯(cuò)誤提示明確,而且還可以進(jìn)行功能擴(kuò)展。
三、技術(shù)實(shí)現(xiàn)
1. 環(huán)境配置
在調(diào)試程序前,需要安裝必要的Python模塊,主要是python-docx, openpyxl和smtplib。python-docx用于讀取、寫入docx文件,openpyxl用于讀取Excel文件的內(nèi)容, smtiplib主要用于郵件群發(fā)。
# 安裝必要的Python庫 pip install python-docx openpyxl smtplib
2. 智能切分文檔
在文檔翻譯的切分策略上,與傳統(tǒng)的CAT工具基于任務(wù)分配的方式不同,我采取了以完整段落為基礎(chǔ)、同時(shí)兼顧翻譯量控制的處理原則。
通過限定每個(gè)切分文件中的單詞數(shù)量,不僅有效降低了不同文件之間詞數(shù)的波動(dòng)幅度,也避免了譯員接收到割裂的段落內(nèi)容,從而在整體上保障了翻譯過程的連貫性與質(zhì)量穩(wěn)定性。
經(jīng)過與DeepSeek的多回合對話,再加上程序的調(diào)試,我們編寫出了注釋清楚、功能全面的文檔切分代碼,如下所示:
import os
import re
from docx import Document
from pathlib import Path
def create_output_directory(base_dir="切分文件"):
"""創(chuàng)建輸出目錄,如果不存在則自動(dòng)創(chuàng)建"""
if not os.path.exists(base_dir):
os.makedirs(base_dir)
print(f"創(chuàng)建目錄: {base_dir}")
return base_dir
def count_english_words(text):
"""精確計(jì)算英文單詞數(shù)量(專業(yè)級處理)"""
# 專業(yè)思考:翻譯行業(yè)的單詞計(jì)數(shù)需要包含連字符單詞
# 如"state-of-the-art"計(jì)為1個(gè)單詞,而非4個(gè)
words = re.findall(r'\b[a-zA-Z\']+(?:-[a-zA-Z]+)*\b', text)
return len(words)
def split_docx_by_word_count(input_file, words_per_file=10000):
"""
智能切分Word文檔,自動(dòng)創(chuàng)建目錄并按規(guī)則命名
參數(shù):
input_file: 輸入文件路徑
words_per_file: 每個(gè)文件的單詞數(shù)目標(biāo)
返回:
生成的文件列表
"""
# 創(chuàng)建輸出目錄
output_dir = create_output_directory("切分文件")
# 獲取原文件名(不含擴(kuò)展名)
original_name = Path(input_file).stem
try:
doc = Document(input_file)
file_count = 1
current_word_count = 0
current_doc = Document()
output_files = []
print(f"開始處理文檔: {input_file}")
print(f"目標(biāo)字?jǐn)?shù): {words_per_file}詞/文件")
for i, paragraph in enumerate(doc.paragraphs):
if not paragraph.text.strip():
continue
paragraph_word_count = count_english_words(paragraph.text)
# 專業(yè)思考:保持段落完整性,避免在段落中間切分
if current_word_count + paragraph_word_count > words_per_file and current_word_count > 0:
# 保存當(dāng)前文件
output_filename = f"{original_name}{file_count}.docx"
output_path = os.path.join(output_dir, output_filename)
current_doc.save(output_path)
output_files.append(output_path)
print(f"生成文件: {output_filename} (字?jǐn)?shù): {current_word_count})")
# 創(chuàng)建新文件
file_count += 1
current_doc = Document()
current_word_count = 0
# 添加段落到當(dāng)前文檔
current_doc.add_paragraph(paragraph.text)
current_word_count += paragraph_word_count
# 保存最后一個(gè)文件
if current_word_count > 0:
output_filename = f"{original_name}{file_count}.docx"
output_path = os.path.join(output_dir, output_filename)
current_doc.save(output_path)
output_files.append(output_path)
print(f"生成文件: {output_filename} (字?jǐn)?shù): {current_word_count})")
print(f"切分完成!共生成 {len(output_files)} 個(gè)文件")
return output_files
except Exception as e:
print(f"文檔處理出錯(cuò): {str(e)}")
return []在代碼中,通過利用正則表達(dá)式【\b[a-zA-Z\']+(?:-[a-zA-Z]+)*\b】,排除數(shù)字、標(biāo)點(diǎn)等符號(hào)的影響,精準(zhǔn)檢索字母,連字符或所有格符號(hào)組成的英語單詞,在限制函數(shù)split_docx_by_word_count中添加默認(rèn)分割標(biāo)準(zhǔn),限制words_per_file的單詞數(shù)量為10000詞。切分后的文檔以原文名+數(shù)字序號(hào)來命名,存儲(chǔ)在切分文檔文件夾中備用。
3. 名單匹配與驗(yàn)證模塊
驗(yàn)證環(huán)節(jié),我們設(shè)計(jì)在發(fā)送翻譯任務(wù)前需要進(jìn)行任務(wù)數(shù)量和譯員數(shù)量的匹配檢查,避免了分配錯(cuò)誤帶來的后續(xù)麻煩,這正是項(xiàng)目管理經(jīng)驗(yàn)的代碼化體現(xiàn)。
調(diào)試前要制作譯員名單Excel文件,分別設(shè)置姓名和郵箱兩個(gè)字段名,放入與翻譯文件數(shù)相同的譯員數(shù)量并仔細(xì)核對姓名和郵箱。
以下代碼將從Excel文件的第二行開始讀取譯員信息,同時(shí)與上一個(gè)流程中生成的output_files數(shù)量進(jìn)行核對,如果不一致就停止發(fā)送,直到滿足翻譯任務(wù)與譯員數(shù)量的匹配要求。
import openpyxl
def read_translator_list(excel_file):
"""
讀取譯員名單Excel文件
格式要求:第一列姓名,第二列郵箱
"""
try:
workbook = openpyxl.load_workbook(excel_file)
sheet = workbook.active
translators = []
for row_num, row in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2):
if row[0] and row[1]: # 確保姓名和郵箱都不為空
translators.append({
'name': str(row[0]).strip(),
'email': str(row[1]).strip(),
'row': row_num # 記錄行號(hào)便于排查問題
})
elif row[0] or row[1]: # 只有一個(gè)字段有內(nèi)容
print(f"警告: 第{row_num}行信息不完整")
print(f"從Excel讀取到 {len(translators)} 位譯員")
return translators
except Exception as e:
print(f"讀取Excel文件失敗: {str(e)}")
return []
def validate_assignment(translators, output_files):
"""
驗(yàn)證譯員數(shù)量與文件數(shù)量是否匹配
"""
translator_count = len(translators)
file_count = len(output_files)
print("\n" + "="*50)
print("分配驗(yàn)證檢查")
print("="*50)
print(f"譯員數(shù)量: {translator_count}")
print(f"文件數(shù)量: {file_count}")
if translator_count == file_count:
print("? 驗(yàn)證通過:譯員數(shù)量與文件數(shù)量匹配")
return True
elif translator_count > file_count:
print(f"? 驗(yàn)證失?。鹤g員數(shù)量({translator_count})多于文件數(shù)量({file_count})")
print(f" 請?jiān)黾?{translator_count - file_count} 個(gè)文件或減少譯員")
else:
print(f"? 驗(yàn)證失?。何募?shù)量({file_count})多于譯員數(shù)量({translator_count})")
print(f" 請減少 {file_count - translator_count} 個(gè)文件或增加譯員")
return False4. 智能批量郵件發(fā)送
在這一部分,我們需要安裝smtplib郵件群發(fā)模塊的同時(shí)獲取發(fā)件人的名稱、郵箱地址、郵件服務(wù)器地址、端口信息、密鑰信息等內(nèi)容。翻譯任務(wù)將以附件的形式發(fā)送,同時(shí)附帶郵件模板,明確譯者人名、翻譯任務(wù)、翻譯時(shí)效等信息,用戶不用登錄郵箱即可實(shí)現(xiàn)翻譯任務(wù)的郵件群發(fā)。
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.header import Header
import traceback
import time
def send_translation_assignments(smtp_config, translators, output_files):
"""
批量發(fā)送翻譯任務(wù)郵件(增強(qiáng)版)
"""
success_count = 0
failed_emails = []
print(f"\n開始發(fā)送任務(wù)郵件...")
# 任務(wù)信息配置
task_info = {
'deadline': 7,
'style': '技術(shù)文檔的嚴(yán)謹(jǐn)性',
'project_name': '翻譯項(xiàng)目',
'word_count': 12000,
'manager_name': smtp_config.get('sender_name', '項(xiàng)目經(jīng)理')
}
for i, translator in enumerate(translators):
if i < len(output_files): # 安全邊界檢查
attachment_file = output_files[i]
translator_name = translator['name']
translator_email = translator['email']
print(f"正在發(fā)送給: {translator_name} ({translator_email})")
if send_single_email(smtp_config, translator_name, translator_email, attachment_file, task_info):
success_count += 1
# 添加延遲,避免發(fā)送頻率過高被限制
if i < len(translators) - 1: # 最后一個(gè)不需要延遲
time.sleep(2)
else:
failed_emails.append(f"{translator_name}({translator_email})")
# 發(fā)送結(jié)果匯總
print(f"\n" + "="*50)
print("郵件發(fā)送完成!")
print("="*50)
print(f"成功: {success_count}/{len(translators)}")
if failed_emails:
print(f"失敗的收件人:")
for failed in failed_emails:
print(f" ? {failed}")
else:
print("? 所有郵件發(fā)送成功!")
return success_count
def send_single_email(smtp_config, name, email, attachment_file, task_info):
"""發(fā)送單個(gè)郵件(增強(qiáng)版)"""
try:
# 創(chuàng)建多部分郵件對象
msg = MIMEMultipart()
# 設(shè)置郵件頭(符合企業(yè)郵箱規(guī)范)
display_name = smtp_config.get('display_name', '翻譯項(xiàng)目管理中心')
msg['From'] = f"{Header(display_name, 'utf-8').encode()} <{smtp_config['sender_email']}>"
msg['To'] = email
msg['Subject'] = Header(f"翻譯任務(wù)分配 - {name}", 'utf-8')
# 郵件正文
email_content = f"""
尊敬的{name}:
您好!
您分配到的翻譯任務(wù)文件請見附件。
任務(wù)要求:
1. 請?jiān)趝task_info['deadline']}個(gè)工作日內(nèi)完成翻譯
2. 保持術(shù)語一致性,請參考術(shù)語表
3. 翻譯風(fēng)格請保持{task_info['style']}
4. 如有問題請及時(shí)與我溝通
文件信息:{os.path.basename(attachment_file)}
項(xiàng)目名稱:{task_info['project_name']}
單詞數(shù)量:約{task_info['word_count']}詞
請確認(rèn)收到本郵件及附件,謝謝!
祝工作順利!
{task_info['manager_name']}
"""
msg.attach(MIMEText(email_content, 'plain', 'utf-8'))
# 添加附件
if not os.path.isfile(attachment_file):
print(f" ? 附件不存在: {attachment_file}")
return False
try:
with open(attachment_file, "rb") as f:
filename = os.path.basename(attachment_file)
part = MIMEApplication(f.read())
part.add_header('Content-Disposition', 'attachment',
filename=('utf-8', '', filename))
msg.attach(part)
print(f" ? 已添加附件: {filename}")
except Exception as e:
print(f" ? 添加附件失敗: {attachment_file} | 錯(cuò)誤: {str(e)}")
return False
# 建立加密連接并發(fā)送
try:
with smtplib.SMTP_SSL(smtp_config['server'], smtp_config['port']) as server:
server.login(smtp_config['sender_email'], smtp_config['password'])
server.sendmail(smtp_config['sender_email'], [email], msg.as_string())
print(f" ? 發(fā)送成功")
return True
except smtplib.SMTPAuthenticationError:
print(f" ? 郵箱認(rèn)證失敗,請檢查賬號(hào)密碼")
except smtplib.SMTPRecipientsRefused:
print(f" ? 收件人被拒絕,可能郵箱不存在")
except smtplib.SMTPException as e:
print(f" ? SMTP錯(cuò)誤: {str(e)}")
except Exception as e:
print(f" ? 連接錯(cuò)誤: {str(e)}")
except Exception as e:
print(f" ? 郵件構(gòu)造錯(cuò)誤: {str(e)}")
traceback.print_exc()
return False 5. 主控程序參數(shù)配置
這一部分主要是控制翻譯任務(wù)分派流程,配置郵件群發(fā)參數(shù),返回潛在的報(bào)錯(cuò)信息,便于掌握程序運(yùn)行進(jìn)度,并及時(shí)排除有可能存在的問題。
def main():
"""主程序 - 項(xiàng)目管理自動(dòng)化入口"""
print("=" * 60)
print(" 翻譯項(xiàng)目智能分派系統(tǒng)")
print("=" * 60)
# 配置參數(shù)
config = {
'input_file': 'project.docx', # 原始項(xiàng)目文件
'excel_file': 'translators.xlsx', # 譯員名單
'words_per_file': 10000, # 每個(gè)文件1萬詞
# 郵箱配置(根據(jù)實(shí)際情況修改)
'smtp': {
'server': 'smtp.163.com',
'port': 587,
'sender_email': 'your_email@163.com',
'sender_name': '張項(xiàng)目經(jīng)理',
'password': 'your_password'
}
}
# 執(zhí)行流程
print("步驟1: 文件切分...")
output_files = split_docx_by_word_count(config['input_file'], config['words_per_file'])
if not output_files:
print("文件切分失敗,程序退出")
return
print("\n步驟2: 讀取譯員名單...")
translators = read_translator_list(config['excel_file'])
if not translators:
print("讀取譯員名單失敗,程序退出")
return
print("\n步驟3: 分配驗(yàn)證...")
if validate_assignment(translators, output_files):
print("\n步驟4: 發(fā)送任務(wù)郵件...")
send_translation_assignments(config['smtp'], translators, output_files)
else:
print("\n?? 分配驗(yàn)證未通過,請調(diào)整后重新運(yùn)行程序")
print("建議:")
if len(translators) > len(output_files):
print(" - 增加輸入文檔內(nèi)容")
print(" - 或從Excel中移除部分譯員")
else:
print(" - 減少每個(gè)文件的字?jǐn)?shù)目標(biāo)")
print(" - 或在Excel中添加更多譯員")
if __name__ == "__main__":
main()三、使用方法
1. 文件準(zhǔn)備
項(xiàng)目原始文檔:project.docx, 確保是.docx格式
譯員名單信息:translators.xlsx,確保有姓名和郵箱兩個(gè)字段
切分詞數(shù):words_per_file: 10000, 限制10000詞
確保以上文件與py程序在同一目錄下面。
2. 環(huán)境配置
修改main()函數(shù)中的郵箱配置,并確保網(wǎng)絡(luò)連接正常。

郵箱配置信息
3. 調(diào)試代碼
根據(jù)報(bào)錯(cuò)信息,進(jìn)行代碼修正,直到能夠成功運(yùn)行代碼,順利完成原始文檔的切分和分配任務(wù)。運(yùn)行中發(fā)現(xiàn)譯員數(shù)量過少,可以添加譯員信息,與翻譯任務(wù)匹配,最終實(shí)現(xiàn)正常發(fā)送。

調(diào)試代碼
修改代碼后,正常運(yùn)行結(jié)果示意如下:

翻譯項(xiàng)目智能分派系統(tǒng)
收到的郵件信息如下:

群發(fā)郵件截圖
四、代碼展示
以下是通過調(diào)用阿里云郵件群發(fā)服務(wù)實(shí)現(xiàn)的文件切分、計(jì)量、核對、群發(fā)功能的樣例代碼:
import os
import re
from docx import Document
from pathlib import Path
import openpyxl
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.header import Header
import traceback
import time
def create_output_directory(base_dir="切分文件"):
"""創(chuàng)建輸出目錄,如果不存在則自動(dòng)創(chuàng)建"""
if not os.path.exists(base_dir):
os.makedirs(base_dir)
print(f"創(chuàng)建目錄: {base_dir}")
return base_dir
def count_english_words(text):
"""精確計(jì)算英文單詞數(shù)量(專業(yè)級處理)"""
# 專業(yè)思考:翻譯行業(yè)的單詞計(jì)數(shù)需要包含連字符單詞
# 如"state-of-the-art"計(jì)為1個(gè)單詞,而非4個(gè)
words = re.findall(r'\b[a-zA-Z\']+(?:-[a-zA-Z]+)*\b', text)
return len(words)
def split_docx_by_word_count(input_file, words_per_file=10000):
"""
智能切分Word文檔,自動(dòng)創(chuàng)建目錄并按規(guī)則命名
參數(shù):
input_file: 輸入文件路徑
words_per_file: 每個(gè)文件的單詞數(shù)目標(biāo)
返回:
生成的文件列表
"""
# 創(chuàng)建輸出目錄
output_dir = create_output_directory("切分文件")
# 獲取原文件名(不含擴(kuò)展名)
original_name = Path(input_file).stem
try:
doc = Document(input_file)
file_count = 1
current_word_count = 0
current_doc = Document()
output_files = []
print(f"開始處理文檔: {input_file}")
print(f"目標(biāo)字?jǐn)?shù): {words_per_file}詞/文件")
for i, paragraph in enumerate(doc.paragraphs):
if not paragraph.text.strip():
continue
paragraph_word_count = count_english_words(paragraph.text)
# 專業(yè)思考:保持段落完整性,避免在段落中間切分
if current_word_count + paragraph_word_count > words_per_file and current_word_count > 0:
# 保存當(dāng)前文件
output_filename = f"{original_name}{file_count}.docx"
output_path = os.path.join(output_dir, output_filename)
current_doc.save(output_path)
output_files.append(output_path)
print(f"生成文件: {output_filename} (字?jǐn)?shù): {current_word_count})")
# 創(chuàng)建新文件
file_count += 1
current_doc = Document()
current_word_count = 0
# 添加段落到當(dāng)前文檔
current_doc.add_paragraph(paragraph.text)
current_word_count += paragraph_word_count
# 保存最后一個(gè)文件
if current_word_count > 0:
output_filename = f"{original_name}{file_count}.docx"
output_path = os.path.join(output_dir, output_filename)
current_doc.save(output_path)
output_files.append(output_path)
print(f"生成文件: {output_filename} (字?jǐn)?shù): {current_word_count})")
print(f"切分完成!共生成 {len(output_files)} 個(gè)文件")
return output_files
except Exception as e:
print(f"文檔處理出錯(cuò): {str(e)}")
return []
def read_translator_list(excel_file):
"""
讀取譯員名單Excel文件
格式要求:第一列姓名,第二列郵箱
"""
try:
workbook = openpyxl.load_workbook(excel_file)
sheet = workbook.active
translators = []
for row_num, row in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2):
if row[0] and row[1]: # 確保姓名和郵箱都不為空
translators.append({
'name': str(row[0]).strip(),
'email': str(row[1]).strip(),
'row': row_num # 記錄行號(hào)便于排查問題
})
elif row[0] or row[1]: # 只有一個(gè)字段有內(nèi)容
print(f"警告: 第{row_num}行信息不完整")
print(f"從Excel讀取到 {len(translators)} 位譯員")
return translators
except Exception as e:
print(f"讀取Excel文件失敗: {str(e)}")
return []
def validate_assignment(translators, output_files):
"""
驗(yàn)證譯員數(shù)量與文件數(shù)量是否匹配
"""
translator_count = len(translators)
file_count = len(output_files)
print("\n" + "="*50)
print("分配驗(yàn)證檢查")
print("="*50)
print(f"譯員數(shù)量: {translator_count}")
print(f"文件數(shù)量: {file_count}")
if translator_count == file_count:
print("? 驗(yàn)證通過:譯員數(shù)量與文件數(shù)量匹配")
return True
elif translator_count > file_count:
print(f"? 驗(yàn)證失?。鹤g員數(shù)量({translator_count})多于文件數(shù)量({file_count})")
print(f" 請?jiān)黾?{translator_count - file_count} 個(gè)文件或減少譯員")
else:
print(f"? 驗(yàn)證失敗:文件數(shù)量({file_count})多于譯員數(shù)量({translator_count})")
print(f" 請減少 {file_count - translator_count} 個(gè)文件或增加譯員")
return False
def send_translation_assignments(smtp_config, translators, output_files):
"""
批量發(fā)送翻譯任務(wù)郵件(增強(qiáng)版)
"""
success_count = 0
failed_emails = []
print(f"\n開始發(fā)送任務(wù)郵件...")
# 任務(wù)信息配置
task_info = {
'deadline': 7,
'style': '技術(shù)文檔的嚴(yán)謹(jǐn)性',
'project_name': '翻譯項(xiàng)目',
'word_count': 12000,
'manager_name': smtp_config.get('sender_name', '項(xiàng)目經(jīng)理')
}
for i, translator in enumerate(translators):
if i < len(output_files): # 安全邊界檢查
attachment_file = output_files[i]
translator_name = translator['name']
translator_email = translator['email']
print(f"正在發(fā)送給: {translator_name} ({translator_email})")
if send_single_email(smtp_config, translator_name, translator_email, attachment_file, task_info):
success_count += 1
# 添加延遲,避免發(fā)送頻率過高被限制
if i < len(translators) - 1: # 最后一個(gè)不需要延遲
time.sleep(2)
else:
failed_emails.append(f"{translator_name}({translator_email})")
# 發(fā)送結(jié)果匯總
print(f"\n" + "="*50)
print("郵件發(fā)送完成!")
print("="*50)
print(f"成功: {success_count}/{len(translators)}")
if failed_emails:
print(f"失敗的收件人:")
for failed in failed_emails:
print(f" ? {failed}")
else:
print("? 所有郵件發(fā)送成功!")
return success_count
def send_single_email(smtp_config, name, email, attachment_file, task_info):
"""發(fā)送單個(gè)郵件(增強(qiáng)版)"""
try:
# 創(chuàng)建多部分郵件對象
msg = MIMEMultipart()
# 設(shè)置郵件頭(符合企業(yè)郵箱規(guī)范)
display_name = smtp_config.get('display_name', '翻譯項(xiàng)目管理中心')
msg['From'] = f"{Header(display_name, 'utf-8').encode()} <{smtp_config['sender_email']}>"
msg['To'] = email
msg['Subject'] = Header(f"翻譯任務(wù)分配 - {name}", 'utf-8')
# 郵件正文
email_content = f"""
尊敬的{name}:
您好!
您分配到的翻譯任務(wù)文件請見附件。
任務(wù)要求:
1. 請?jiān)趝task_info['deadline']}個(gè)工作日內(nèi)完成翻譯
2. 保持術(shù)語一致性,請參考術(shù)語表
3. 翻譯風(fēng)格請保持{task_info['style']}
4. 如有問題請及時(shí)與我溝通
文件信息:{os.path.basename(attachment_file)}
項(xiàng)目名稱:{task_info['project_name']}
單詞數(shù)量:約{task_info['word_count']}詞
請確認(rèn)收到本郵件及附件,謝謝!
祝工作順利!
{task_info['manager_name']}
"""
msg.attach(MIMEText(email_content, 'plain', 'utf-8'))
# 添加附件
if not os.path.isfile(attachment_file):
print(f" ? 附件不存在: {attachment_file}")
return False
try:
with open(attachment_file, "rb") as f:
filename = os.path.basename(attachment_file)
part = MIMEApplication(f.read())
part.add_header('Content-Disposition', 'attachment',
filename=('utf-8', '', filename))
msg.attach(part)
print(f" ? 已添加附件: {filename}")
except Exception as e:
print(f" ? 添加附件失敗: {attachment_file} | 錯(cuò)誤: {str(e)}")
return False
# 建立加密連接并發(fā)送
try:
with smtplib.SMTP_SSL(smtp_config['server'], smtp_config['port']) as server:
server.login(smtp_config['sender_email'], smtp_config['password'])
server.sendmail(smtp_config['sender_email'], [email], msg.as_string())
print(f" ? 發(fā)送成功")
return True
except smtplib.SMTPAuthenticationError:
print(f" ? 郵箱認(rèn)證失敗,請檢查賬號(hào)密碼")
except smtplib.SMTPRecipientsRefused:
print(f" ? 收件人被拒絕,可能郵箱不存在")
except smtplib.SMTPException as e:
print(f" ? SMTP錯(cuò)誤: {str(e)}")
except Exception as e:
print(f" ? 連接錯(cuò)誤: {str(e)}")
except Exception as e:
print(f" ? 郵件構(gòu)造錯(cuò)誤: {str(e)}")
traceback.print_exc()
return False
def main():
"""主程序 - 項(xiàng)目管理自動(dòng)化入口"""
print("=" * 60)
print(" 翻譯項(xiàng)目智能分派系統(tǒng)")
print("=" * 60)
# 配置參數(shù)
config = {
'input_file': 'input.docx', # 原始項(xiàng)目文件
'excel_file': 'email.xlsx', # 譯員名單
'words_per_file': 10000, # 每個(gè)文件1萬詞
# 郵箱配置(根據(jù)實(shí)際情況修改)
'smtp': {
'server': 'smtpdm.aliyun.com',
'port': 465,
'sender_email': 'Your Email Address',
'sender_name': '李項(xiàng)目經(jīng)理',
'display_name': '翻譯項(xiàng)目管理中心', # 新增:發(fā)件人顯示名稱
'password': 'Your Password'
}
}
# 執(zhí)行流程
print("步驟1: 文件切分...")
output_files = split_docx_by_word_count(config['input_file'], config['words_per_file'])
if not output_files:
print("文件切分失敗,程序退出")
return
print("\n步驟2: 讀取譯員名單...")
translators = read_translator_list(config['excel_file'])
if not translators:
print("讀取譯員名單失敗,程序退出")
return
print("\n步驟3: 分配驗(yàn)證...")
if validate_assignment(translators, output_files):
print("\n步驟4: 發(fā)送任務(wù)郵件...")
send_translation_assignments(config['smtp'], translators, output_files)
else:
print("\n?? 分配驗(yàn)證未通過,請調(diào)整后重新運(yùn)行程序")
print("建議:")
if len(translators) > len(output_files):
print(" - 增加輸入文檔內(nèi)容")
print(" - 或從Excel中移除部分譯員")
else:
print(" - 減少每個(gè)文件的字?jǐn)?shù)目標(biāo)")
print(" - 或在Excel中添加更多譯員")
if __name__ == "__main__":
main()五、總結(jié)
翻譯項(xiàng)目智能分派系統(tǒng)充分發(fā)揮DeepSeek大模型代碼撰寫功能,根據(jù)翻譯項(xiàng)目管理中的實(shí)際需求,編寫特定Python代碼,用于任務(wù)的自動(dòng)化分派,優(yōu)化了傳統(tǒng)翻譯工作流程,有效解決了翻譯項(xiàng)目管理過程中的實(shí)際痛點(diǎn),為廣大翻譯學(xué)習(xí)者和項(xiàng)目經(jīng)理們提供了一個(gè)完整的、可復(fù)用的項(xiàng)目實(shí)操案例。
當(dāng)然,本系統(tǒng)可能存在文件格式保留不完善,缺少UI界面,功能不夠全面,僅適用于英語文本的分派等問題,未來可以進(jìn)一步擴(kuò)展為帶有UI界面,支持漢語文本,兼具翻譯項(xiàng)目切分和分派功能的小軟件,還可集成大模型在線翻譯功能,進(jìn)一步簡化翻譯流程。
在數(shù)字化浪潮下,為順應(yīng)時(shí)代的發(fā)展和翻譯技術(shù)的迭代更新,翻譯專業(yè)人員應(yīng)掌握一定的Python編程技術(shù),借助日新月異的AI編程助手,提升技術(shù)運(yùn)用能力來解決翻譯流程中的個(gè)性與共性問題,從而實(shí)現(xiàn)從被動(dòng)接受工具的用戶,向主動(dòng)創(chuàng)造解決方案的賦能者轉(zhuǎn)化。唯有如此,我們才能在這個(gè)瞬息萬變的時(shí)代中,在專業(yè)的道路上走得行穩(wěn)致遠(yuǎn)。
以上就是巧用Python實(shí)現(xiàn)自動(dòng)化翻譯任務(wù)分配詳解的詳細(xì)內(nèi)容,更多關(guān)于Python自動(dòng)化翻譯的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python Excel 通用篩選函數(shù)的實(shí)現(xiàn)
本文主要介紹了Python Excel 通用篩選函數(shù)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-08-08
python實(shí)現(xiàn)unicode轉(zhuǎn)中文及轉(zhuǎn)換默認(rèn)編碼的方法
這篇文章主要介紹了python實(shí)現(xiàn)unicode轉(zhuǎn)中文及轉(zhuǎn)換默認(rèn)編碼的方法,結(jié)合實(shí)例形式分析了Python針對Unicode編碼操作的相關(guān)技巧及編碼轉(zhuǎn)換中的常見問題解決方法,需要的朋友可以參考下2017-04-04
Python 存取npy格式數(shù)據(jù)實(shí)例
這篇文章主要介紹了Python 存取npy格式數(shù)據(jù)實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
Django Admin 管理工具的實(shí)現(xiàn)
這篇文章主要介紹了Django Admin 管理工具的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05

