代码摘录如下
仅供学习
import json
import random
import time
import hashlib
import requests
import re
import os
from urllib import parse
from urllib import request
def trans(content):
# 等待用户输入需要翻译的单词
i = content
# 有道翻译的url链接
url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
# 构造有道的加密参数
client = "fanyideskweb"
ts = int(time.time() * 1000)
salt = str(ts + random.randint(1, 10))
flowerStr = "n%A-rKaT5fb[Gy?;N5@Tj"
sign = hashlib.md5((client + i + salt + flowerStr).encode('utf-8')).hexdigest()
bv = '53539dde41bde18f4a71bb075fcf2e66'
# 创建Form_Data字典,存储请求体
Form_Data = {}
# 需要翻译的文字
Form_Data['i'] = i
# 下面这些都先按照我们之前抓包获取到的数据
Form_Data['from'] = 'AUTO'
Form_Data['to'] = 'AUTO'
Form_Data['smartresult'] = 'dict'
Form_Data['client'] = client
Form_Data['salt'] = salt
Form_Data['sign'] = sign
Form_Data['ts'] = ts
Form_Data['bv'] = bv
Form_Data['doctype'] = 'json'
Form_Data['version'] = '2.1'
Form_Data['keyfrom'] = 'fanyi.web'
Form_Data['action'] = 'FY_BY_REALTIME'
Form_Data['typoResult'] = 'false'
# 对数据进行字节流编码处理
data = parse.urlencode(Form_Data).encode('utf-8')
# 创建Request对象
req = request.Request(url=url, data=data, method='POST')
# 写入header信息
req.add_header('User-Agent',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36')
req.add_header('cookie', 'OUTFOX_SEARCH_USER_ID=-352392290@116.136.20.84')
req.add_header('Referer', 'http://fanyi.youdao.com/')
# 传入创建好的Request对象
response = request.urlopen(req, timeout=5)
# 读取信息并进行字节流解码
html = response.read().decode('utf-8')
print(html)
# 把返回来的json字符串解析成字典
translate_results = json.loads(html)
# 打印翻译结果
translate_result = translate_results["translateResult"][0][0]['tgt']
print("翻译的结果是:%s" % translate_result)
return translate_result
trans('Hey, how are you')
def copy(file, file2):
for root, dirs, files in os.walk(file):
# 遍历文件
for f in files:
time.sleep(random.random())
file_path = os.path.join(root, f)
fi = open(file_path, 'r', encoding='utf-8')
fi2 = open(os.path.join(file2, f), 'w', encoding='utf-8')
while True:
line = fi.readline()
if line.startswith("C_"):
line = re.sub(r'([ws]+)|([^|]+)([.s]+)',
lambda m: m.group(1) + '|' + trans(m.group(2)) + m.group(3), line)
fi2.write(line)
if not line:
fi.close()
fi2.close()
print(f)
break