-
Notifications
You must be signed in to change notification settings - Fork 0
/
translate.py
171 lines (137 loc) · 4.47 KB
/
translate.py
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
'''
This program is for my easy-English translate
Date:2018/10/8
Author:ivan1rufus
'''
import urllib.request
import urllib.parse
import tkinter
import requests
import bs4
import re
import json
import pickle
from bs4 import BeautifulSoup as Bs
#Already import tkinter, prepare for the gui.
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome\
/69.0.3497.100 Safari/537.36',
}
#Below is for word translate(dictionary)
def dictGetSoup(word, url= 'https://dict.youdao.com/w/eng/'):
url += word
response = requests.get(url, headers=headers)
#print("返回的网页为:" + response.url)
soup = Bs(response.text, 'lxml')
#print(soup)
return soup
def soupProcess(soup):
# First we get the basic meanings of our word
if ord(word[0]) > 256:
basicShow = chnProcess(soup)
else:
basicShow = engProcess(soup)
return basicShow
def engProcess(soup):
basicList = re.findall(r"<li>(.*?)</li>", str(soup))
#print(basicList)
i = 0
while True:
if basicList[i].find('<a') == 0:
basicList.remove(basicList[i])
else:
i += 1
if i == len(basicList):
break
return basicList
def chnProcess(soup):
basicShow = []
soup2 = re.findall(r'<ul>(.*?)</ul>', str(soup), re.DOTALL)[0]
wordGroups = soup2.split('</p>\n<p')
for eachwordGroup in wordGroups:
wordGroup = ''
wordList = []
wordtype = re.findall(r'(?:<.*>)*(.+)</span>', eachwordGroup)
if len(wordtype) > 0:
wordGroup += wordtype[0]
wordGroup += ' '
words = re.findall(r'>([^<]*)</a>', eachwordGroup)
for eachWord in words:
if not (eachWord.find('中法') != -1 or eachWord.find('中日') != -1 \
or eachWord.find('中韩') != -1 or eachWord.find('中英') != -1):
wordGroup += eachWord
if eachWord != words[-1]:
wordGroup += ', '
if len(wordGroup) != 1:
basicShow.append(wordGroup)
return basicShow
def dictionary(word):
soup = dictGetSoup(word)
showList = soupProcess(soup)
show(showList)
englishLearn(word, showList)
def show(showList):
#Basic process
toShow = []
toShow.append('基本释义:')
if len(showList) == 0:
toShow.append('无')
toShow.extend(showList)
toShow.append('')
for eachShow in toShow:
print(eachShow)
#Below is for translating words
def translate(word, url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'):
showList = []
#其实这里用requests包也可以,要注意的是url。实际上接受请求并发送回应的url在Request报文里。
data = {
'i': '怎么',
'from': 'AUTO',
'to': 'AUTO',
'smartresult': 'dict',
'client': 'fanyideskweb',
'salt': '1539356660319',
'sign': '6607a4e010165e79f83811472a173e77',
'doctype': 'json',
'version': '2.1',
'keyfrom': 'fanyi.web',
'action': 'FY_BY_CLICKBUTTION',
'typoResult': 'false'
}
data['i'] = word
data = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url, data=data, headers=headers)
response = urllib.request.urlopen(req)
html = response.read().decode('utf-8')
html = json.loads(html)
showList.append(html['translateResult'][0][0]['tgt'])
#print("使用翻译功能获得的结果为:")
show(showList)
def dictOrTranslate(word):
if word.count(' ')+word.count(' ') >= 2:
translate(word)
else:
dictionary(word)
def englishLearn(word, showList, filename='C:\\Users\\ivan1rufus\\Desktop\\wordsList.txt'):
with open(filename, 'a+') as f:
foundFlag = False
#重定位
f.seek(0)
for eachline in f.readlines():
if eachline.find(word) != '-1':
#eachline.replace(eachline[eachline.index(':')+1], )
foundFlag = True
break
if showList[1] == '无':
foundFlag = True
if foundFlag == False:
newLine = '<' + word + '>' + 'count:0' + '\n'
f.write(newLine)
for eachShow in showList:
f.write(eachShow + '\n')
if __name__ == '__main__':
while True:
word = input('想翻译啥?<如果想使用翻译功能,请在输入中加入两个或以上的空格>\n')
if word == 'sb':
break
dictOrTranslate(word)