Python实现单词翻译功能 在进行英文文献阅读时,经常会出现一些不认识的单词,但对于一些pdf阅读器,比如Foxit阅读器使用翻译功能需要点击(Extra->Translate),并且启用了翻译功能将不能使用注释功能,这对于阅读者来说将是极不方便的。所以为了方便查询单词,自己开发了个Windows环境下的Python程序用于监控并查询单词,而只需的操作就是选中单词并按Ctrl+C即可。   该Python程序主要分为三部分:从另外一个应用程序中获取需要查询的单词,单词翻译和单词显示。   从另外一个应用程序中获取需要查询的单词涉及到进程间通信,在Windows上最简单的方法是使用Clipboard功能。Python中有多种方式可以使用剪切板,比如使用win32clipboard(Python使用剪切板的方法)。这里使用的是Qt实现的clipboard,Qt的剪切板实现支持当系统剪切板内容发生改变时回调。具体实现: # 获取Qt的剪切板并绑定回调函数 self.clipboard = QApplication.clipboard() self.clipboard.dataChanged.connect(self.on_clipboard_changed) # 回调函数 def on_clipboard_changed(self): data = self.clipboard.mimeData() if data.hasText(): word = data.text().strip() m = re.match(r'[a-zA-Z]+', word) if m: self.setWord(word) #self.setWindowFlags(self.windowFlags() & QtCore.Qt.WindowStaysOnTopHint) #self.setWindowState(self.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive) trans = queryWords(word) self.setTrans(trans) ''' tip the window content has changed, but cannot move the window to the forground''' self.activateWindow() else: print(word)   单词翻译直接调用有道单词翻译,单词翻译的链接格式为http://dict.youdao.com/w/{}/,其中{}为需要查询的单词。获取的将是单个网页,使用BeautifulSoup提取最终的翻译结果。 def queryWords(word): ''' 利用有道翻译查询单词 ''' url = 'http://dict.youdao.com/w/{}/'.format(word) html = getURL(url) soup = BeautifulSoup(html.text, 'html.parser') trans_container = soup.find(class_='trans-container') if not trans_container: ''' not found the translation ''' return [word] trans_li = trans_container.find_all('li') trans_data = [li.text.strip() for li in trans_li] return trans_data   最后显示是通过Qt编写的界面,原本是想查询到单词后,界面窗口自动激活并移动到最前端,但Windows不允许未经用户操作而将窗口移动到最前端,所以最后只是通过激活窗口提示用户。   完整的代码位于http://github.com/llf2017/pyDict/blob/master/pyDict.py 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持中文源码网。