LLM文本转换全攻略:翻译、校对、格式转换与语气调整一站式搞定(附代码)
摘要
大语言模型不仅是生成文本的高手,更是“文本转换”的全能工具。本文基于 OpenAI 官方课程,系统讲解如何利用 LLM 完成四大类转换任务:语言翻译(单语种、多语种、正式/非正式语气区分)、拼写与语法校对(批量纠错、差异对比、风格升级)、格式转换(JSON 转 HTML 表格)、语气转换(俚语转商务信函)。通过丰富的代码示例和实战技巧,你将学会构建通用翻译器、自动化校对系统,并掌握提示词优化的关键方法。所有代码均基于 gpt-3.5-turbo 模型。
适用人群 / 前置知识
适用人群:需要处理多语言内容、校对文档、转换数据格式的开发者、内容运营、产品经理;希望提升 LLM 应用能力的 AI 爱好者。
前置知识:Python 基础;OpenAI API 调用基础(如前几篇博客所述);了解 JSON、HTML 基本格式。
引言:文本转换——LLM 的“瑞士军刀”
在过去,如果你需要将一段 JSON 转换成 HTML 表格,你可能要写一个复杂的模板引擎;如果你想纠正一篇文章的语法错误,你需要 Grammarly 或人工校对;如果你想将一句话同时翻译成五种语言,你得调用多个翻译 API。而现在,大语言模型用一个提示词就能完成所有这些任务。
本文将带你逐一探索 LLM 的四大转换能力:
- 语言翻译:单语种、多语种、区分正式/非正式语气
- 拼写与语法校对:自动纠错、批量处理、风格提升
- 格式转换:JSON ↔ HTML、Markdown、XML 等
- 语气转换:俚语 ↔ 商务信函、调整受众
环境准备
复用之前的辅助函数,并支持可选的 temperature 参数(转换任务一般用 0):
import openai
import os
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())
openai.api_key = os.getenv('OPENAI_API_KEY')
def get_completion(prompt, model="gpt-3.5-turbo", temperature=0):
messages = [{"role": "user", "content": prompt}]
response = openai.ChatCompletion.create(
model=model,
messages=messages,
temperature=temperature,
)
return response.choices[0].message["content"]
一、语言翻译
1.1 基础翻译
prompt = f"""
将以下英文文本翻译成西班牙语:
```Hi, I would like to order a blender```
"""
response = get_completion(prompt)
print(response)
# 输出:Hola, me gustaría ordenar una licuadora
1.2 语言识别
prompt = f"""
告诉我这是什么语言:
```Combien coûte le lampadaire?```
"""
response = get_completion(prompt)
print(response)
# 输出:这是法语。
1.3 多语种翻译(一次输出多个目标语言)
prompt = f"""
将以下文本翻译成法语、西班牙语和英语海盗语:
```I want to order a basketball```
"""
response = get_completion(prompt)
print(response)
# 输出示例:
# 法语: Je veux commander un ballon de basket
# 西班牙语: Quiero pedir una pelota de baloncesto
# 英语海盗语: I be wantin' to order a basketball
1.4 区分正式与非正式语气
某些语言(如西班牙语、德语、法语)有正式/非正式的人称区分。你可以明确要求模型同时输出两种形式。
prompt = f"""
将以下文本翻译成西班牙语,同时使用正式和非正式形式:
'Would you like to order a pillow?'
"""
response = get_completion(prompt)
print(response)
# 输出:
# 正式: ¿Le gustaría ordenar una almohada?
# 非正式: ¿Te gustaría ordenar una almohada?
1.5 实战:通用翻译器(多语言客服支持)
假设你有一家跨国电商公司,用户用各种语言报告 IT 问题。你可以循环处理每条消息:先识别语言,再翻译成英语和韩语。
user_messages = [
"La performance du système est plus lente que d'habitude.", # 法语
"Mi monitor tiene píxeles que no se iluminan.", # 西班牙语
"Il mio mouse non funziona", # 意大利语
"Mój klawisz Ctrl jest zepsuty", # 波兰语
"我的屏幕在闪烁" # 中文
]
for issue in user_messages:
# 识别语言
prompt_lang = f"告诉我这是什么语言:```{issue}```"
lang = get_completion(prompt_lang)
print(f"原始消息({lang}):{issue}")
# 翻译成英语和韩语
prompt_trans = f"将以下文本翻译成英语和韩语:```{issue}```"
translation = get_completion(prompt_trans)
print(translation, "\n")
运行后,你会看到模型正确识别出法语、西班牙语、意大利语、波兰语和中文,并分别给出英语和韩语翻译。
提示优化:如果你希望语言识别只输出一个词(如 "French"),可以修改提示为:“只用一个词告诉我这是什么语言:...”。
二、语气转换
写作风格可以根据受众调整。例如,将一句随意的俚语转换成正式的商务信函。
prompt = f"""
将以下内容从俚语转换为商务信函:
'Dude, This is Joe, check out this spec on this standing lamp.'
"""
response = get_completion(prompt)
print(response)
输出示例:
Dear Sir or Madam,
I am writing to bring to your attention the specifications for the standing lamp. Please find the details attached.
Sincerely,
Joe
三、格式转换
3.1 JSON 转 HTML 表格
假设你有一个包含员工信息的 JSON 数据,想快速生成一个网页表格。
data_json = {
"restaurant employees": [
{"name": "Shyam", "email": "shyamjaiswal@gmail.com"},
{"name": "Bob", "email": "bob32@gmail.com"},
{"name": "Jai", "email": "jai87@gmail.com"}
]
}
prompt = f"""
将以下 Python 字典从 JSON 转换为带有列标题和标题的 HTML 表格:
{data_json}
"""
response = get_completion(prompt)
print(response)
输出是一个 HTML 字符串。你可以用 IPython.display 渲染:
from IPython.display import display, HTML
display(HTML(response))
你会看到一个漂亮的表格,包含“name”和“email”两列。
扩展:你也可以要求输出 Markdown 表格、XML、CSV 等格式,只需在提示中指定。
四、拼写与语法校对
4.1 批量校对句子列表
texts = [
"The girl with the black and white puppies have a ball.", # 主谓不一致
"Its going to be a long day. Does the car need it's oil changed?", # 所有格与缩略混淆
"Your going to need you're notebook.", # your/you're 错误
"That medicine effects my ability to sleep. Have you heard of the butterfly affect?", # effect/affect 混淆
"This phrase is to cherck chatGPT for speling abilitty" # 拼写错误
]
for t in texts:
prompt = f"""
校对并纠正以下文本,重写纠正后的版本。
如果没有发现错误,只说“未发现错误”。
不要在文本周围使用任何标点符号:
```{t}```
"""
response = get_completion(prompt)
print(response)
模型会输出每个句子的纠正版本,例如:
The girl with the black and white puppies has a ball.
It's going to be a long day. Does the car need its oil changed?
You're going to need your notebook.
...
4.2 校对并高亮差异(使用 redlines 库)
from redlines import Redlines
from IPython.display import Markdown
original_review = """
Got this for my daughter for her birthday cuz she keeps taking mine from my room.
Yes, adults also like pandas too. She takes it everywhere with her, and it's super soft and cute.
One of the ears is a bit lower than the other, and I don't think that was designed to be asymmetrical.
It's a bit small for what I paid for it though. I think there might be other options that are bigger for the same price.
It arrived a day earlier than expected, so I got to play with it myself before I gave it to my daughter.
"""
prompt = f"校对并纠正这条评论:```{original_review}```"
corrected = get_completion(prompt)
diff = Redlines(original_review, corrected)
display(Markdown(diff.output_markdown))
这会生成一个带删除线和下划线的 Markdown 差异视图,清晰显示模型修改了哪些地方。
4.3 高级校对:改变风格、遵循规范
你可以要求模型不仅纠正错误,还调整语气、遵循特定风格指南(如 APA)、面向特定读者。
prompt = f"""
校对并纠正这条评论。使其更具说服力。
确保遵循 APA 风格指南,面向高级读者。
以 Markdown 格式输出。
文本:```{original_review}```
"""
response = get_completion(prompt)
display(Markdown(response))
模型会输出一个更正式、更“高级”的版本,可能包括更丰富的词汇、更严谨的句子结构,并按 APA 格式引用等。
常见问题与注意事项
1. 分隔符的选择:可以使用三重反引号、双引号、尖括号、冒号等,只要清晰一致即可。但注意避免与文本内容中的符号冲突。
2. temperature参数:转换任务(翻译、校对、格式转换)建议 temperature=0,保证确定性输出。语气转换如果需要一定创造性,可适当调高到0.3~0.5。
3. 多语种翻译的质量:GPT-3.5/4 对主流语言(中、英、法、西、德、日、韩等)翻译质量很高,但对低资源语言可能不够准确。建议用少样本提示或切换到更强的模型。
4. 校对时的“过度纠正”:模型有时会把原本正确的表达改成它认为“更标准”的形式。如果你的文本有特定的风格要求,请在提示中明确说明“不要改变原意”或“只纠正明显错误”。
5. 输出解析:当要求输出 HTML 或 JSON 时,建议用正则或 JSON 解析器提取,因为模型可能会额外添加说明文字。
总结
| 转换类型 | 典型提示 | 输出用途 |
|---|---|---|
| 翻译 | Translate … to Spanish | 多语言内容生成 |
| 语言识别 | Tell me what language this is | 自动检测输入语种 |
| 多语种翻译 | Translate to French, Spanish and Korean | 全球化内容分发 |
| 正式/非正式 | Translate … in formal and informal forms | 适配不同社交场景 |
| 语气转换 | Translate from slang to business letter | 邮件、公文写作 |
| 格式转换 | Convert JSON to HTML table | 数据可视化、报表生成 |
| 校对纠错 | Proofread and correct | 文档质量提升 |
| 风格升级 | Make it more compelling, follow APA style | 学术写作、营销文案 |
LLM 的文本转换能力,让过去需要多种工具、多套流程才能完成的任务,统一成一个简单的 API 调用。无论是构建国际化产品、自动化内容处理,还是提升写作质量,这些技巧都能为你节省大量时间和精力。
下一步,你可以尝试将这些转换能力组合起来——例如,先翻译用户评论,再对其做情感分析,然后将结果转换为 HTML 报表。无限可能,尽在提示词中。
更多推荐


所有评论(0)