文科生自学 python 两个月,还是看不懂代码,不知道怎么添加想要的内容:
网上抄了一段代码,想在运行之后,直接输出英文和中文内容, 第 43 行的 print 只有原文件的英文内容,如果同时 print 出中文,需要如何修改,谢谢大家,
文科生的极限实在没法,来这里求帮忙
def translateBaidu(content, fromLang='en', toLang='zh'): salt = str(random.randint(32768, 65536)) sign = appid + content + salt + secretKey sign = hashlib.md5(sign.encode("utf-8")).hexdigest()
try:
paramas = {
'appid': appid,
'q': content,
'from': fromLang,
'to': toLang,
'salt': salt,
'sign': sign
}
response = requests.get(apiurl, paramas)
jsonResponse = response.json() # 得到返回的结果,结果为 json 格式
dst: str = str(jsonResponse["trans_result"]
[0]["dst"]) # 取得翻译后的文本结果
return dst
except Exception as e:
print(e)
def excelTrans(srcFilename=r'/Users/justin/Desktop/FANYI.xlsx', desFilename=r'/Users/justin/Desktop/FANYI1.xlsx', srcSheet='Sheet1', srcColumn=1, srcRowBegin=1, srcRowEnd=402, desColumn=1, desSheet='中文品名'): wb = openpyxl.load_workbook(srcFilename) ws = wb[srcSheet] wb2 = Workbook() ws2 = wb2.create_sheet(title=desSheet)
for i in range(srcRowBegin, srcRowEnd, 1):
result = ws.cell(row=i, column=srcColumn).value
if not (result is None):
ws2.cell(row=i-srcRowBegin+1,
column=desColumn).value = translateBaidu(result)
print(result)
wb2.save(desFilename)
if name == 'main': print('translate begin...') excelTrans() print('ending...')
1
justincnn OP print(result) 之后只有原文件的英文,没有中文,这个怎么修改啊,
|
2
Vibra 2020-11-17 19:17:13 +08:00 via iPhone
建议 markdown 再写一遍。
|
3
Wolfsin 2020-11-17 19:20:56 +08:00
|
4
justincnn OP @Wolfsin
def translateBaidu(content, fromLang='en', toLang='zh'): salt = str(random.randint(32768, 65536)) sign = appid + content + salt + secretKey sign = hashlib.md5(sign.encode("utf-8")).hexdigest() try: paramas = { 'appid': appid, 'q': content, 'from': fromLang, 'to': toLang, 'salt': salt, 'sign': sign } response = requests.get(apiurl, paramas) jsonResponse = response.json() # 得到返回的结果,结果为 json 格式 dst: str = str(jsonResponse["trans_result"] [0]["dst"]) # 取得翻译后的文本结果 return dst except Exception as e: print(e) def excelTrans(srcFilename=r'/Users/justin/Desktop/FANYI.xlsx', desFilename=r'/Users/justin/Desktop/FANYI1.xlsx', srcSheet='Sheet1', srcColumn=1, srcRowBegin=1, srcRowEnd=2, desColumn=1, desSheet='中文品名'): wb = openpyxl.load_workbook(srcFilename) ws = wb[srcSheet] wb2 = Workbook() ws2 = wb2.create_sheet(title=desSheet) for i in range(srcRowBegin, srcRowEnd, 1): result = ws.cell(row=i, column=srcColumn).value if not (result is None): ws2.cell(row=i-srcRowBegin+1, column=desColumn).value = translateBaidu(result) print(result+"translate is done") wb2.save(desFilename) if __name__ == '__main__': print('translate begin...') excelTrans() print('ending...') |
5
kermitlee 2020-11-17 19:24:35 +08:00
这应该是调用了百度翻译的接口,看代码你的返回结果应该是存在了 /Users/justin/Desktop/FANYI1.xlsx 这份文件里,如果你需要打印翻译的结果的话,去看这行代码 translateBaidu(result) 的返回结果,翻译结果应该就是在这里。
|
7
Wolfsin 2020-11-17 19:36:23 +08:00
我也觉得结果应该在 translateBaidu(result),这个函数的返回值里面,你应该 print(translateBaidu(result)),或者 print(column)看看
|