mport requests
import time
from models_exp import NewWord
class Translate:
def __init__(self):
# self.util = Utils()
pass
# translation api, tranlate a english word to chinese
# return translation result
# 百度翻译接口
def _trans(self, word):
# res = self.trans.translate('hello', dest='zh-CN')
url = 'http://fanyi.baidu.com/sug'
dct = {'kw': word}
req = requests.post(url, dct)
req.raise_for_status()
res = req.json().get('data')
if not res:
return None
return res[0].get('v', None)
# iciba api / 金山词典 api
# baidu api dont contain Phonogram , so change an api
def _trans_ici(self, word):
url = 'http://www.iciba.com/index.php?a=getWordMean&c=search&word=' + word
try:
req = requests.get(url)
req.raise_for_status()
info = req.json()
data = info['baesInfo']['symbols'][0]
assert info['baesInfo']['symbols'][0]
# 去除没有音标的单词
assert data['ph_am'] and data['ph_en']
# 去除没有词性的单词
assert data['parts'][0]['part']
except:
return ('none','none')
ph_en = '英 [' + data['ph_en'] + ']'
ph_am = '美 [' + data['ph_am'] + ']'
ex = ''
for part in data['parts']:
ex += part['part'] + ';'.join(part['means']) + ';'
return ph_en+ph_am, ex
# 扇贝单词 api
def _trans_shanbay(self, word):
url = 'https://api.shanbay.com/bdc/search/?word=' + word
req = requests.get(url)
print(req.json())
# 使用 金山单词 翻译接口
# 百度接口没有音标
# 扇贝接口包含的信息不如其他两家
def trans(self):
query = NewWord.select().where(NewWord.explanation != '')
if not query:
return
for word in query:
res = self._trans_ici(word.name)
# print(res)
if res:
word.phonogram = res[0]
# word.
word.explanation = res[1]
else:
word.is_valid = False
word.save()
time.sleep(1)
if __name__ == '__main__':
t = Translate()
# res = t._trans_shanbay('hello')
# print(res)
# t.trans()
res = t._trans_ici('hello')
print(res[1])
#写代码遍历修改数据库
for i in NewWord.select():
print(i.name,end=' ')
exp = str(t._trans_ici(i.name)[1])
i.explanation = exp
#print(i.explanation)
i.save()
单词统计查询(3.translate.py)
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 1,先实现多表查询: (可以发现两个集合发生了乘积,这叫笛卡尔积问题。) 消除笛卡尔积: (这只是消除了显示的笛卡...
- 【蝴蝶效应】 蝴蝶效应:上个世纪70年代,美国一个名叫洛伦兹的气象学家在解释空气系统理论时说,亚马逊雨林一只蝴蝶...