本文目录导读:

我来提供几种实现快捷短语替换的脚本方案,从简单到复杂:
方案1:Python 简单替换脚本
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
快捷短语替换工具
用法: python replace_phrases.py <输入文件> <输出文件>
"""
import sys
import re
import json
# 定义快捷短语映射
PHRASES = {
"gm": "早上好",
"gn": "晚安",
"thx": "谢谢",
"pls": "请",
"btw": "顺便说一下",
"afaik": "据我所知",
"idk": "我不知道",
"imho": "依我愚见",
"ttyl": "以后再聊",
"wyd": "你在做什么",
# 可以添加更多
}
def replace_phrases(text):
"""替换文本中的快捷短语"""
# 单词边界匹配,避免替换单词中间的部分
pattern = r'\b(' + '|'.join(re.escape(k) for k in PHRASES.keys()) + r')\b'
return re.sub(pattern, lambda m: PHRASES[m.group(1)], text, flags=re.IGNORECASE)
def main():
if len(sys.argv) != 3:
print("用法: python replace_phrases.py <输入文件> <输出文件>")
sys.exit(1)
input_file = sys.argv[1]
output_file = sys.argv[2]
try:
with open(input_file, 'r', encoding='utf-8') as f:
content = f.read()
result = replace_phrases(content)
with open(output_file, 'w', encoding='utf-8') as f:
f.write(result)
print(f"替换完成!已保存到 {output_file}")
except FileNotFoundError:
print(f"错误: 找不到文件 {input_file}")
sys.exit(1)
if __name__ == "__main__":
main()
方案2:支持自定义短语配置
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
快捷短语替换工具(支持自定义配置)
配置文件格式 (JSON):
{
"phrases": {
"gm": "早上好",
"thx": "谢谢"
},
"case_sensitive": false
}
"""
import sys
import re
import json
import os
class PhraseReplacer:
def __init__(self, config_file='phrases.json'):
self.phrases = {}
self.case_sensitive = False
self.load_config(config_file)
def load_config(self, config_file):
"""加载配置文件"""
try:
if os.path.exists(config_file):
with open(config_file, 'r', encoding='utf-8') as f:
config = json.load(f)
self.phrases = config.get('phrases', {})
self.case_sensitive = config.get('case_sensitive', False)
print(f"已加载 {len(self.phrases)} 个快捷短语")
else:
# 默认配置
self.phrases = {
"gm": "早上好",
"gn": "晚安",
"thx": "谢谢",
"pls": "请",
"btw": "顺便说一下"
}
print("使用默认快捷短语配置")
except Exception as e:
print(f"配置加载错误: {e}")
sys.exit(1)
def replace(self, text):
"""替换文本中的快捷短语"""
if not self.phrases:
return text
# 构建替换模式
keys = sorted(self.phrases.keys(), key=len, reverse=True)
pattern = r'\b(' + '|'.join(re.escape(k) for k in keys) + r')\b'
if not self.case_sensitive:
pattern = r'(?i)' + pattern
# 替换函数
def replacer(match):
word = match.group(0)
if self.case_sensitive:
return self.phrases[word]
else:
# 保持原大小写形式
original = match.group(1)
replacement = self.phrases[original.lower()]
if original[0].isupper():
replacement = replacement.capitalize()
return replacement
return re.sub(pattern, replacer, text)
def main():
if len(sys.argv) < 2:
print("用法:")
print(" python phrase_replacer.py <输入文件> [输出文件]")
print("如果未指定输出文件,将直接输出到屏幕")
sys.exit(1)
replacer = PhraseReplacer()
input_file = sys.argv[1]
try:
with open(input_file, 'r', encoding='utf-8') as f:
content = f.read()
result = replacer.replace(content)
if len(sys.argv) >= 3:
output_file = sys.argv[2]
with open(output_file, 'w', encoding='utf-8') as f:
f.write(result)
print(f"替换完成!已保存到 {output_file}")
else:
print("替换结果:")
print("-" * 50)
print(result)
except FileNotFoundError:
print(f"错误: 找不到文件 {input_file}")
sys.exit(1)
if __name__ == "__main__":
main()
方案3:交互式快速替换
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
交互式快捷短语替换工具
"""
import os
import sys
import keyboard # 需要: pip install keyboard
class QuickPhraseReplacer:
def __init__(self):
self.phrases = {
'gm': '早上好',
'gn': '晚安',
'thx': '谢谢',
'pls': '请',
'btw': '顺便说一下',
'afaik': '据我所知',
'idk': '我不知道',
'imho': '依我愚见',
'ttyl': '以后再聊',
'wyd': '你在做什么',
'w/': 'with',
'w/o': 'without',
'b/c': 'because',
'etc.': '等等',
'i.e.': '也就是说',
'e.g.': '#39;,
}
self.buffer = ""
self.trigger_char = ';' # 触发字符
def on_key_press(self, key):
"""键盘事件处理"""
if hasattr(key, 'name'):
# 特殊键
if key.name == 'space':
self.check_buffer()
self.buffer = ""
return
elif key.name == 'enter':
self.check_buffer()
self.buffer = ""
return
else:
return
# 普通字符
char = getattr(key, 'char', '')
if char == self.trigger_char:
self.replace_last_word()
self.buffer = ""
elif char:
self.buffer += char
def check_buffer(self):
"""检查缓冲区中的快捷短语"""
if self.buffer in self.phrases:
# 这里是简化版,实际应用需要模拟退格和输入
print(f"\n[替换: {self.buffer} -> {self.phrases[self.buffer]}]")
self.buffer = ""
def replace_last_word(self):
"""替换最后一个单词"""
# 这个功能在真实键盘监听中较复杂
# 这里仅作为演示
pass
def start(self):
"""启动监听"""
print("快捷短语替换工具已启动 (按 ESC 退出)")
print(f"定义的快捷短语: {list(self.phrases.keys())}")
print("输入快捷短语后按空格或回车自动替换")
print("-" * 50)
try:
keyboard.on_press(self.on_key_press)
keyboard.wait('esc') # 按 ESC 退出
except KeyboardInterrupt:
pass
finally:
print("\n已退出")
def create_phrases_config():
"""创建默认配置文件"""
config = {
"phrases": {
"gm": "早上好",
"gn": "晚安",
"thx": "谢谢",
"btw": "顺便说一下",
"idk": "我不知道"
},
"case_sensitive": false
}
with open('phrases.json', 'w', encoding='utf-8') as f:
json.dump(config, f, ensure_ascii=False, indent=2)
print("已创建配置文件 phrases.json")
if __name__ == "__main__":
replacer = QuickPhraseReplacer()
# 创建配置文件(如果需要)
if not os.path.exists('phrases.json'):
command = input("是否创建配置文件? (y/n): ")
if command.lower() == 'y':
create_phrases_config()
replacer.start()
方案4:GUI版本(Tkinter)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
快捷短语替换工具 - GUI版本
"""
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import json
import os
class PhraseReplacerGUI:
def __init__(self, root):
self.root = root
self.root.title("快捷短语替换工具")
self.root.geometry("800x600")
# 加载配置
self.phrases = self.load_phrases()
self.setup_ui()
def load_phrases(self):
"""加载快捷短语"""
default_phrases = {
"gm": "早上好",
"gn": "晚安",
"thx": "谢谢",
"pls": "请",
"btw": "顺便说一下"
}
if os.path.exists('phrases.json'):
try:
with open('phrases.json', 'r', encoding='utf-8') as f:
config = json.load(f)
return config.get('phrases', default_phrases)
except:
return default_phrases
return default_phrases
def setup_ui(self):
"""设置UI"""
# 主容器
main_frame = ttk.Frame(self.root, padding="10")
main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# 输入区域
ttk.Label(main_frame, text="输入文本:").grid(row=0, column=0, sticky=tk.W)
self.input_text = scrolledtext.ScrolledText(main_frame, height=10, width=70)
self.input_text.grid(row=1, column=0, columnspan=3, pady=5)
# 按钮区域
button_frame = ttk.Frame(main_frame)
button_frame.grid(row=2, column=0, columnspan=3, pady=10)
ttk.Button(button_frame, text="替换", command=self.replace_text).pack(side=tk.LEFT, padx=5)
ttk.Button(button_frame, text="清空", command=self.clear_text).pack(side=tk.LEFT, padx=5)
ttk.Button(button_frame, text="管理短语", command=self.manage_phrases).pack(side=tk.LEFT, padx=5)
ttk.Button(button_frame, text="保存配置", command=self.save_config).pack(side=tk.LEFT, padx=5)
# 短语列表
ttk.Label(main_frame, text="快捷短语列表:").grid(row=3, column=0, sticky=tk.W, pady=(10,0))
self.phrases_listbox = tk.Listbox(main_frame, width=50, height=10)
self.phrases_listbox.grid(row=4, column=0, columnspan=3, pady=5)
self.refresh_phrases_list()
# 输出区域
ttk.Label(main_frame, text="替换结果:").grid(row=5, column=0, sticky=tk.W, pady=(10,0))
self.output_text = scrolledtext.ScrolledText(main_frame, height=10, width=70)
self.output_text.grid(row=6, column=0, columnspan=3, pady=5)
# 设置网格权重
self.root.columnconfigure(0, weight=1)
self.root.rowconfigure(0, weight=1)
main_frame.columnconfigure(0, weight=1)
main_frame.rowconfigure(1, weight=1)
def replace_text(self):
"""执行替换"""
import re
text = self.input_text.get("1.0", tk.END)
# 构建替换模式
keys = sorted(self.phrases.keys(), key=len, reverse=True)
pattern = r'\b(' + '|'.join(re.escape(k) for k in keys) + r')\b'
def replacer(match):
return self.phrases[match.group(1)]
result = re.sub(pattern, replacer, text, flags=re.IGNORECASE)
self.output_text.delete("1.0", tk.END)
self.output_text.insert("1.0", result)
def clear_text(self):
"""清空输入输出"""
self.input_text.delete("1.0", tk.END)
self.output_text.delete("1.0", tk.END)
def refresh_phrases_list(self):
"""刷新短语列表"""
self.phrases_listbox.delete(0, tk.END)
for key, value in self.phrases.items():
self.phrases_listbox.insert(tk.END, f"{key} -> {value}")
def manage_phrases(self):
"""管理短语"""
dialog = tk.Toplevel(self.root)
dialog.title("管理快捷短语")
dialog.geometry("400x300")
dialog.transient(self.root)
dialog.grab_set()
# 添加新短语
add_frame = ttk.Frame(dialog, padding="10")
add_frame.pack(fill=tk.X)
ttk.Label(add_frame, text="快捷符:").pack(side=tk.LEFT)
key_entry = ttk.Entry(add_frame, width=15)
key_entry.pack(side=tk.LEFT, padx=5)
ttk.Label(add_frame, text="替换为:").pack(side=tk.LEFT)
value_entry = ttk.Entry(add_frame, width=20)
value_entry.pack(side=tk.LEFT, padx=5)
def add_phrase():
key = key_entry.get().strip()
value = value_entry.get().strip()
if key and value:
self.phrases[key] = value
self.refresh_phrases_list()
messagebox.showinfo("成功", f"已添加: {key} -> {value}")
dialog.destroy()
else:
messagebox.showwarning("警告", "请输入快捷符和替换内容")
ttk.Button(add_frame, text="添加", command=add_phrase).pack(side=tk.LEFT, padx=5)
# 删除短语
delete_frame = ttk.Frame(dialog, padding="10")
delete_frame.pack(fill=tk.X)
def delete_phrase():
selection = self.phrases_listbox.curselection()
if selection:
item = self.phrases_listbox.get(selection[0])
key = item.split(" -> ")[0]
del self.phrases[key]
self.refresh_phrases_list()
messagebox.showinfo("成功", f"已删除: {key}")
ttk.Button(delete_frame, text="删除选中", command=delete_phrase).pack()
def save_config(self):
"""保存配置"""
config = {
"phrases": self.phrases,
"case_sensitive": False
}
try:
with open('phrases.json', 'w', encoding='utf-8') as f:
json.dump(config, f, ensure_ascii=False, indent=2)
messagebox.showinfo("成功", "配置已保存到 phrases.json")
except Exception as e:
messagebox.showerror("错误", f"保存失败: {e}")
def main():
root = tk.Tk()
app = PhraseReplacerGUI(root)
root.mainloop()
if __name__ == "__main__":
main()
使用方法
命令行版本
# 创建短语配置文件 python create_config.py # 替换文件内容 python phrase_replacer.py input.txt output.txt
GUI版本
python phrase_replacer_gui.py
配置文件格式 (phrases.json)
{
"phrases": {
"gm": "早上好",
"gn": "晚安",
"thx": "谢谢",
"btw": "顺便说一下"
},
"case_sensitive": false
}
选择适合你需求的方案,如果需要进一步调整,请告诉我!
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播