89 lines
2.4 KiB
Python
89 lines
2.4 KiB
Python
import random
|
|
import hashlib
|
|
import requests
|
|
import time
|
|
|
|
|
|
def baidu_translate(word):
|
|
api_url = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
|
|
# 百度翻译appid
|
|
# appid = '20230629001728201'
|
|
# # api的密码
|
|
# secretKey = 'mTOyai8ueVnmkdZ3atRj'
|
|
appid = '20230607001703210'
|
|
secretKey = 'neGN1Q7ZLi1TLSM4YIpM'
|
|
salt = random.randint(32768, 65536)
|
|
str1 = (appid + word + str(salt) + secretKey)
|
|
md = hashlib.md5()
|
|
md.update(str1.encode('utf-8'))
|
|
sign = md.hexdigest()
|
|
# 可以设置翻译的语言
|
|
api_data = {
|
|
'q': word,
|
|
'from': 'cht',
|
|
'to': 'en',
|
|
'appid': appid,
|
|
'salt': salt,
|
|
'sign': sign
|
|
}
|
|
req_get = requests.get(api_url, api_data)
|
|
# 结果的位置可能不同
|
|
result_json = req_get.json()
|
|
result: str = ''
|
|
if 'trans_result' in result_json:
|
|
result = result_json['trans_result'][0]['dst']
|
|
return result
|
|
|
|
|
|
def spider(filepath, suffix):
|
|
import os
|
|
code_files = []
|
|
for root, dirs, files in os.walk(filepath, topdown=False):
|
|
for f in files:
|
|
file = os.path.join(root, f)
|
|
if file.endswith(suffix):
|
|
code_files.append(file.replace("\\", "/"))
|
|
return code_files
|
|
|
|
|
|
def message(code_files):
|
|
msgs = []
|
|
for i in code_files:
|
|
fp = open(i, 'r', encoding='utf-8')
|
|
data = fp.readlines()
|
|
for line in data:
|
|
curr_code = line.strip('\n')
|
|
if curr_code is None:
|
|
curr_code = line.strip('\r\n')
|
|
msgs.append(curr_code)
|
|
return msgs
|
|
|
|
|
|
if __name__ == '__main__':
|
|
code_files = spider('/Users/liaozetao/Downloads/message', '.txt')
|
|
msgs = message(code_files)
|
|
for m in msgs:
|
|
while True:
|
|
try:
|
|
if len(m) == 0:
|
|
continue
|
|
arr = m.split(', ')
|
|
str1: str = ''
|
|
if len(arr) > 0:
|
|
str1 = arr[0]
|
|
str2: str = ''
|
|
if len(arr) > 1:
|
|
str2 = arr[1]
|
|
if len(str2) == 0:
|
|
continue
|
|
else:
|
|
str2 = str2.split(')')[0]
|
|
str2 = str2.replace('"', '')
|
|
content = baidu_translate(str2)
|
|
print(str1, ', "', content, '"),')
|
|
time.sleep(1)
|
|
break
|
|
except Exception as e:
|
|
print(e)
|
|
continue
|