本文目录导读:

我来为你介绍几种编写自动润色语句脚本的方法,从简单到复杂:
基于规则的简单润色(Python)
import re
class TextPolisher:
def __init__(self):
self.fixes = [
(r'\s+', ' '), # 压缩多余空格
(r'\s*([.,!?:;])\s*', r'\1 '), # 标点后加空格
(r'\(\s+', '('), # 去除括号前空格
(r'\s+\)', ')'), # 去除括号后空格
]
self.typo_fixes = {
'teh': 'the',
'recieve': 'receive',
'beleive': 'believe',
}
def polish(self, text):
# 修复空格问题
for pattern, replacement in self.fixes:
text = re.sub(pattern, replacement, text)
# 修复常见错别字
for wrong, correct in self.typo_fixes.items():
text = re.sub(r'\b' + wrong + r'\b', correct, text, flags=re.IGNORECASE)
return text.strip()
# 使用示例
polisher = TextPolisher()
text = " The cat is sleeping . I recieve a gift "
result = polisher.polish(text)
print(result) # The cat is sleeping. I receive a gift
使用NLP库的增强版(NLTK + TextBlob)
from textblob import TextBlob
import nltk
class NLPPolisher:
def __init__(self):
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
def polish(self, text):
blob = TextBlob(text)
# 自动修正拼写错误
corrected = blob.correct()
# 首字母大写
sentences = corrected.sentences
polished = []
for sent in sentences:
# 首句首字母大写
if len(polished) == 0:
sent_str = str(sent).capitalize()
else:
sent_str = str(sent)
# 确保句末有标点
if not sent_str[-1] in '.!?':
sent_str += '.'
polished.append(sent_str)
return ' '.join(polished)
# 使用示例
polisher = NLPPolisher()
text = "i am go to school yesterday. he is a good student"
result = polisher.polish(text)
print(result)
使用OpenAI API的高级润色
import openai
from typing import Optional
class AIPolisher:
def __init__(self, api_key: str):
openai.api_key = api_key
def polish(self,
text: str,
style: str = "formal",
tone: str = "neutral") -> str:
prompts = {
"formal": "请将以下文本润色为正式风格:",
"casual": "请将以下文本润色为更自然的口语风格:",
"academic": "请将以下文本润色为学术风格:",
"business": "请将以下文本润色为商务风格:"
}
prompt = prompts.get(style, prompts["formal"])
prompt += f"\n\n{text}"
if tone == "friendly":
prompt += "\n\n请保持友好和温暖的语气。"
elif tone == "professional":
prompt += "\n\n请保持专业和客观的语气。"
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "你是一个专业的文本润色助手。"},
{"role": "user", "content": prompt}
],
max_tokens=len(text) * 2,
temperature=0.7
)
return response.choices[0].message.content
except Exception as e:
return f"润色失败:{str(e)}"
# 使用示例
# polisher = AIPolisher("your-api-key")
# result = polisher.polish("I wanna go to the party but i am tired")
完整的GUI应用(Tkinter)
import tkinter as tk
from tkinter import ttk, scrolledtext
from textblob import TextBlob
class TextPolisherApp:
def __init__(self, root):
self.root = root
self.root.title("AI文本润色工具")
self.root.geometry("800x600")
# 创建界面
self.create_widgets()
def create_widgets(self):
# 输入区域
ttk.Label(self.root, text="输入文本:").pack(pady=5)
self.input_text = scrolledtext.ScrolledText(
self.root, height=10, width=80
)
self.input_text.pack(pady=10)
# 选项区域
options_frame = ttk.Frame(self.root)
options_frame.pack(pady=10)
ttk.Label(options_frame, text="润色方式:").grid(row=0, column=0, padx=5)
self.style_var = tk.StringVar(value="basic")
ttk.Radiobutton(options_frame, text="基础润色",
variable=self.style_var, value="basic").grid(row=0, column=1, padx=5)
ttk.Radiobutton(options_frame, text="拼写纠正",
variable=self.style_var, value="spell").grid(row=0, column=2, padx=5)
ttk.Radiobutton(options_frame, text="完整润色",
variable=self.style_var, value="full").grid(row=0, column=3, padx=5)
# 按钮
button_frame = ttk.Frame(self.root)
button_frame.pack(pady=10)
ttk.Button(button_frame, text="开始润色",
command=self.polish_text).pack(side=tk.LEFT, padx=5)
ttk.Button(button_frame, text="清空",
command=self.clear_text).pack(side=tk.LEFT, padx=5)
# 输出区域
ttk.Label(self.root, text="润色结果:").pack(pady=5)
self.output_text = scrolledtext.ScrolledText(
self.root, height=10, width=80
)
self.output_text.pack(pady=10)
def polish_text(self):
text = self.input_text.get("1.0", tk.END).strip()
if not text:
return
style = self.style_var.get()
if style == "basic":
# 基础润色 - 修正空格和标点
result = self.basic_polish(text)
elif style == "spell":
# 拼写纠正
result = self.spell_correct(text)
else:
# 完整润色
result = self.full_polish(text)
self.output_text.delete("1.0", tk.END)
self.output_text.insert("1.0", result)
def basic_polish(self, text):
# 基础润色逻辑
import re
text = re.sub(r'\s+', ' ', text)
text = text.strip()
# 确保首字母大写
text = text[0].upper() + text[1:] if text else text
# 确保句末有标点
if text and not text[-1] in '.!?':
text += '.'
return text
def spell_correct(self, text):
from textblob import TextBlob
blob = TextBlob(text)
return str(blob.correct())
def full_polish(self, text):
# 完整润色 - 组合多种方法
text = self.basic_polish(text)
text = self.spell_correct(text)
# 其他优化可以在这里添加
return text
def clear_text(self):
self.input_text.delete("1.0", tk.END)
self.output_text.delete("1.0", tk.END)
if __name__ == "__main__":
root = tk.Tk()
app = TextPolisherApp(root)
root.mainloop()
安装依赖
# 基础版本 pip install textblob nltk # 如果使用OpenAI API pip install openai # 如果使用GUI版本 # tkinter 通常已包含在Python中
使用建议
- 基础润色:适用于修正格式问题
- 拼写纠正:适用于修正拼写错误
- AI润色:适用于需要改变风格或重写句子
- 自定义规则:可以根据需求添加特定规则
选择哪种方法取决于你的具体需求和可用资源,从简单规则到AI辅助都有不同的应用场景。