Python批量键码短语转换脚本

Python 批量键码短语转换脚本

在使用五笔输入法或者自定义短语时,经常需要把“短语 + 键码 + 数量”的格式,批量转换成“键码,数量=短语”的格式,或者反向还原。本文提供一款 双向批量转换 Python 脚本,适合处理大量短语记录。


功能说明

  1. 正向转换(Forward)

原始格式:

FIX
1
短语    键码    数量

转换后格式:

1
键码,数量=短语
  1. 反向转换(Reverse)

原始格式:

FIX
1
键码,数量=短语

转换后格式:

PYTHON
1
短语    键码    数量

脚本内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# -*- coding: utf-8 -*-
"""
双向批量转换脚本
支持:
1. 正向转换:短语+键码+数量 -> 键码,数量=短语
2. 反向转换:键码,数量=短语 -> 短语+键码+数量
"""

import os

# ===== 配置 =====
input_file = "input.txt" # 输入文件路径
output_file = "output.txt" # 输出文件路径
mode = "forward" # 模式: "forward" 或 "reverse"

# ===== 处理 =====
with open(input_file, "r", encoding="utf-8") as f:
lines = f.readlines()

with open(output_file, "w", encoding="utf-8") as f:
for line in lines:
line = line.strip()
if not line:
continue
try:
if mode == "forward":
# 正向转换
parts = line.rsplit("\t", 2)
if len(parts) < 3:
print(f"警告:无法解析此行 -> {line}")
continue
short_phrase = parts[0]
key_code = parts[1]
number = parts[2]
f.write(f"{key_code},{number}={short_phrase}\n")
elif mode == "reverse":
# 反向转换
key_num, short_phrase = line.split("=", 1)
key_code, number = key_num.split(",", 1)
f.write(f"{short_phrase}\t{key_code}\t{number}\n")
else:
raise ValueError("模式错误,请使用 'forward' 或 'reverse'")
except Exception as e:
print(f"处理行出错: {line}\n错误: {e}")

print(f"转换完成,结果已保存到 {output_file}")