因为目前很多厂家提供的程序都是中文注释, 在一些场合下会导致乱码问题, 就花了半天时间写了一个脚本用于批量将 c 语言文件中的注释批量翻译为英文, 一方面可以便于统一注释, 同时也避免了乱码问题。
此代码支持python3.x运行, 只需要在python中加入如下包:
pip install translators
支持转换的注释类型
提醒: 翻译前记得先备份! 如果翻译中网络等出了问题, 则文件可能丢失, 所以一定先做好备份!
首先支持如下几种格式的注释转换(一般正确格式示例)
/*********** 第一个 ****************
* 注释1
* 注释2
**/
int a = 1; // 可转换为英文
int b = 2; /* 正确转换 */
int c = 3; /* 注释1
* 这样也支持
*/
// 转换部分
/* 均可以转换 */
int func(){
}
错误使用和不能转换的情况
首先需要说明的是, 对于转换的注释, 有一定的格式要求, 具体如下 :
- 对于单行注释, 如果单行直接以
//
或者\*
开头, 则会将整行均视为注释, 例如: 如下格式是不允许出现的, 即不建议将注释放在语句后面:
/* 中文注释 */ int a = 1 ;
- 对于多行注释, 每一行均必须以 * 进行开头, 否则将不会进行转换:
/*
* 正确的语句: 此句进行翻译
错误: 此句话不进行翻译
******************/
- 所有注释均尽可能不出现 “;”, 否则将会视为程序语句, 不执行翻译
/*
* 这是多行注释; // 注意: 此处由于加上分号, 则为了避免有
*/
- 不要把分号挪在下一行, 例如
int a = 1 // comment : 正确写法是 int a = 1; + 注释
;
这样可能会导致将前面一并翻译;
代码部分
这个转换注释的代码也是非常简单的, 此处我使用了 bing 作为 translator 的 API, 但有的句子 bing 翻译出会保留部分中文, 则改用 google 引擎翻译。
import os
import re
import time
import warnings
import concurrent.futures
import translators as ts
open_encoding = 'gbk'
dst_encoding = 'utf-8'
max_retry_time = 3
translator = 'bing'
use_google_for_better_trans = True
def translate_comments(file_path):
cnt = 0
with open(file_path, 'r', encoding=open_encoding) as f:
lines = f.readlines()
with open(file_path, 'w', encoding=dst_encoding) as f:
for line in lines:
# Find comments in the line
comments = re.findall(r'//.*|/\* .*|\* .*', line) # also '*' will be captured here
# remove the comments without Chinese Character
comments