开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
develop
分支 (4)
develop
Rivern_Branch
main
release
develop
分支 (4)
develop
Rivern_Branch
main
release
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
develop
分支 (4)
develop
Rivern_Branch
main
release
Community-document
/
translate.py
Community-document
/
translate.py
translate.py 8.42 KB
一键复制 编辑 原始数据 按行查看 历史
chenchi 提交于 2023年04月19日 21:37 +08:00 . 恢复被github强制覆盖的内容
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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
import requests
import random
from hashlib import md5
import time
import os
import sys
import logging
# 日志模块
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# 创建一个handler,用于写入日志文件
rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
log_path = os.path.dirname(os.path.abspath(__file__)) + '/logs/'
log_name = log_path + rq + '.log'
logfile = log_name
fh = logging.FileHandler(logfile, mode='w')
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)
logger.addHandler(fh)
# TODO QuecPython 翻译成Quecpthon了 已解决
# TODO 图片文件不翻译 已解决
# TODO 代码的首字母被大写了 已解决
# TODO 括号被汉化了 已解决
# TODO * * 之间多了个空格 无法正常加粗 已解决
# TODO 对表格处理 翻译后缺失|
# TODO yaml文件也需要补全处理 已解决
# TODO 注释多了个空格 <!-- * --> 已解决
# TODO 目录只翻译前半段 已解决
# Set your own appid/appkey.
appid = '20210722000894813'
appkey = 'QBqv9vS1CIgKSj_foFed'
# For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
# from_lang = 'auto'
from_lang = 'zh'
to_lang = 'en'
endpoint = 'http://api.fanyi.baidu.com'
path = '/api/trans/vip/translate'
url = endpoint + path
# 删除源文档
def delete_txt(file_path):
if os.path.exists(file_path):
try:
os.remove(file_path)
return True
except Exception as e:
info = sys.exc_info()
print("remove file error.", e)
print(info[0], info[1])
return False
else:
return True
# 写文档
def write_txt(file_path, content):
with open(file_path, 'a+', encoding='utf-8') as f:
f.write(content)
# 判断是否有中文字符
def check_contain_chinese(check_str):
for ch in check_str.decode('utf-8'):
if u'\u4e00' <= ch <= u'\u9fff':
return True
return False
# 用于保持和原文一样的格式(only for code-)
def space_str_handle(space_str):
# count = ''
# for i in space_str:
# if i == '#':
# count += ' '
# continue
# else:
# print('count:', len(count))
# return [count, space_str]
space_str_list = space_str.split('#', 1)
return space_str_list
# 用于保持和原文一样的格式 for yaml
def space_yaml_handle(space_str):
count = ''
for i in space_str:
if i == ' ':
count += ' '
continue
else:
# print('count:', len(count))
return [count, space_str]
# 用于处理路径翻译部分(路径不能翻译,翻译会多很多空格)
def space_path_handle(space_str: str) -> list:
if space_str.find('](') != -1:
print(space_str)
index = space_str.index(']')
return [space_str[:index+1], space_str[index+1:]]
else:
return [space_str, '']
# 获取英语翻译-> 百度翻译
def get_english(words: str) -> str:
"""
功能: 源语言(自动识别)=> 英语
传入翻译文字,自动识别,翻译后返回一个列表,每个元素为一段落
"""
# Set your own appid/appkey.
query = words
# Generate salt and sign
def make_md5(s, encoding='utf-8'):
return md5(s.encode(encoding)).hexdigest()
salt = random.randint(32768, 65536)
sign = make_md5(appid + query + str(salt) + appkey)
# Build request
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}
# Send request
time.sleep(2)
try:
r = requests.post(url, params=payload, headers=headers)
result = r.json()
print(result)
trans = result['trans_result']
ret = ''
for n in range(len(trans)):
ret += trans[n]['dst']
# 解决专用名词翻译问题
ret = ret.replace('Quecpthon', 'QuecPython')
except Exception as e:
ret = query
print(e)
logger.info('翻译失败的大哥:' + ret)
logger.info('翻译失败的原因:' + str(e))
return ret
# 从文件中取翻译内容
def main(src_path):
out_path = src_path.replace('zh', 'en')
code_flag = False
for line in open(src_path, 'r', encoding='utf-8'):
line = line.strip('\n')
if len(line) < 1: # 该行仅仅是换行
write_txt(out_path, "\n")
else:
# 图片文件路径不翻译(翻译后找不到文件了)
if line.startswith('!['):
write_txt(out_path, line + "\n")
continue
if line == '```python':
code_flag = True
if line == '```':
code_flag = False
if check_contain_chinese(line.encode('utf-8')):
# print(code_flag)
if code_flag:
line = space_str_handle(line)
if len(line) == 2:
print('待翻译内容:', line[1])
data = get_english(line[1])
write_txt(out_path, line[0] + '#' + data + "\n") # 百度API 方法
else:
print('待翻译内容:', line[0])
data = get_english(line[0])
write_txt(out_path, data + "\n") # 百度API 方法
else:
if line[0] == " ": # 不是目录
line = space_yaml_handle(line)
print('待翻译内容:', line[1])
data = get_english(line[1])
write_txt(out_path, line[0] + tran_handler(data) + "\n")
else:
line = space_path_handle(line)
print('待翻译内容:', line[0])
data = get_english(line[0])
write_txt(out_path, tran_handler(data) + line[1] + "\n")
else:
write_txt(out_path, line + "\n")
# 处理md格式问题 ####后面加空格
def tran_handler(hanle_str):
hanle_str = hanle_str.replace('* * *', '**') # 去除翻译过程中产生多余的空格(有时候会多一个)
hanle_str = hanle_str.replace('* *', '**') # 去除翻译过程中产生多余的空格
hanle_str = hanle_str.replace('- >', '-->') # 补全翻译过程缺失的内容
hanle_str = hanle_str.replace('-Label', '- label') # 补全翻译过程缺失的内容
# hanle_str = hanle_str.replace('] (', '](') # 补全翻译过程缺失的内容
if hanle_str.startswith('#'):
count = 0
for j in hanle_str:
if j == "#":
count += 1
continue
else:
break
str_list = list(hanle_str)
str_list.insert(count, " ")
return ''.join(str_list)
else:
return hanle_str
if __name__ == '__main__':
# 单个文件
root_list = 'E:\\teedoc_wiki\\新版文档中心\\Community-document\\docs\\sbs\\zh\\README.md'
delete_txt(root_list.replace('zh', 'en')) # 删除原文件
main(root_list)
# 单层目录
# root_list = 'E:\\teedoc_wiki\\新版文档中心\\Community-document\\docs\\FAQ\\zh'
# for root, dirs, files in os.walk(root_list, topdown=False):
# for name in files:
# if name.split(".")[-1] in ('md', 'yaml'):
# # print(os.path.join(root, name))
# delete_txt(os.path.join(root, name).replace('zh', 'en')) # 删除原文件
# main(os.path.join(root, name))
# time.sleep(5)
# 整个项目
# root_path = 'E:\\teedoc_wiki\\新版文档中心\\Community-document\\docs\\'
# root_list = os.listdir(root_path)
# for i in root_list:
# print(os.path.join(root_path, i))
# for root, dirs, files in os.walk(os.path.join(root_path, i+'\\zh'), topdown=False):
# for name in files:
# if name.split(".")[-1] in ('md', 'yaml'):
# delete_txt(os.path.join(root, name).replace('zh', 'en')) # 删除原文件
# main(os.path.join(root, name))
# time.sleep(5)
# 传参
# if len(sys.argv) < 2:
# print('No input file provided')
# exit()
# if sys.argv[1] == 'all':
# # 翻译全部
# pass
# else:
# # 单个文件
# pass
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

QuecPython 文档中心源文件
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/quecpython/Community-document.git
git@gitee.com:quecpython/Community-document.git
quecpython
Community-document
Community-document
develop
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /