python自动化英语查词

前一阵子在看Automate the Boring Stuff with Python,读英语文章时会碰到不认识的单词,需要复制英文,查询对应的中文解释。再把英文及中文解释复制到文章的右边方便查阅,如此重复很多次,相当烦人。就想试着用python实现按住Crtl+C,然后自动在记事本中生成对应的单词和意思,省去复制黏贴的繁琐无意义劳动。先演示最终成果查词小程序
用PyQt5实现GUI界面
在这里插入图片描述

用CMD操作
在这里插入图片描述

OneNote做的笔记
示意图
程序的初步设想是利用python读取剪切板的内容(复制的英文单词),写入txt文件,然后对文件里的内容进行整理,在利用beautiful soup进行单词意思的搜索并将中英文写入文件。
首先使用cmd实现

#运行程序,复制单词,自动生成中英文对照
import pyperclip,pyautogui,msvcrt,requests, webbrowser, bs4,os,subprocess
#对重复内容进行整理
def  rearrange():
     playFile.close()
     with open('word.txt') as f:
         File = open('wenzi.txt','w')
         list = f.read().splitlines()
         lines=[]
         for i in list:
             if i not in lines:
                lines.append(i)
         for lines in lines:
             File.write(lines+"\n")
         File.close()
         playFile.close()


print('Press Esc to translate.')
print('Press blank space to revise.')
#读取剪切板
str = pyperclip.paste()
#打开word.txt用于写入复制的文本
playFile = open('word.txt','a+')
i=0
while True:
    #每当剪切板内容发生变化的时候将单词写入word.txt
    #一个单词限制只写入一次
    #未知原因依然会出现重复内容,调用reanrrange进行整理
    #整理后的内容写人wenzi.txt
    if i==0:
        playFile.write(str+"\n")
        print(str);i=1
    if str!=pyperclip.paste():
        i=0
        str = pyperclip.paste()
    #通过键盘决定翻译或修改并跳出循环
    #Esc键translate,空格键revise
    if msvcrt.kbhit():
      if ord(msvcrt.getch()) == 27:
         rearrange()
         break
      if ord(msvcrt.getch()) == 32:
         rearrange()
         subprocess.call("wenzi.txt",shell=True)
         input("whether the wenzi.txt is correct")
         break
    #删除word.txt
os.remove("word.txt")
#打开wenzi.txt
with open('wenzi.txt') as f:
 #一行一行的读取内容
    lines = f.read().splitlines()
    #借助有道词典进行翻译
    for i in range(len(lines)):
        res = requests.get('https://www.youdao.com/w/eng/' + lines[i]+'/#keyfrom=dict2.index')
        res.raise_for_status()
        exampleSoup = bs4.BeautifulSoup(res.text)
        type(exampleSoup)
        elems = exampleSoup.select('#phrsListTab .trans-container ul li')
        #写入eco.txt
        playFile = open('eco.txt','a')
        playFile.write(lines[i]+" : ")
        for elems in elems:
          str=elems.getText()
          playFile.write(str+" ")
        playFile.write("\n")
        playFile.close()
    #打开eco.txt
os.remove("wenzi.txt")
subprocess.call("eco.txt",shell=True)

无图形界面不适合用户使用,初步学习GUI编程使用Pyqt5实现

import sys,subprocess,os,requests, webbrowser, bs4
from PyQt5 import QtWidgets
#使用请一次性复制完所有的单词,该程序会自动记录
class MainUI():
    def __init__(self):
        self.cb = QtWidgets.QApplication.clipboard()

    #信号cb.dataChanged
    def setupFunction(self):
        self.cb.dataChanged.connect(self.cb_changed)

    #槽lable.setText(str)
    def cb_changed(self):
        str=self.cb.text()
        lable.setText(str)
        playFile = open('word.txt','a+')
        playFile.write(str+"\n")
        playFile.close()

def button1Clicked():
    if count==0:
        rearrange()
    subprocess.call("wenzi.txt",shell=True)

def button2Clicked():       
    if count==0:
        rearrange()
    with open('wenzi.txt',"r+") as f:
        lines = f.read().splitlines()
        File = open('eco.txt','a')
        for i in range(len(lines)):
            res = requests.get('https://www.youdao.com/w/eng/' + lines[i]+'/#keyfrom=dict2.index')
            res.raise_for_status()
            exampleSoup = bs4.BeautifulSoup(res.text)
            type(exampleSoup)
            elems = exampleSoup.select('#phrsListTab .trans-container ul li')
            File.write(lines[i]+" : ")
            for elems in elems:
                str=elems.getText()
                File.write(str+" ")
            File.write("\n")
        File.close()
        f.close()
    with open('wenzi.txt',"r+") as F:    
        F.truncate()
        F.close()
    subprocess.call("eco.txt",shell=True)
      
def  rearrange():
    #def使用全局变量变量需要global
    global count
    count=1
    #设计为一次性的搜索,故中断连接
    ui.cb.dataChanged.disconnect()
    with open('word.txt') as wj:
         F = open('wenzi.txt','w')
         list = wj.read().splitlines()
         lines=[]
         for i in list:
             if i not in lines:
                lines.append(i)
         for lines in lines:
             F.write(lines+"\n")
         F.close()
         wj.close()
    os.remove("word.txt")

if __name__ == "__main__":
    #固定模板
    app = QtWidgets.QApplication(sys.argv)
    count=0
    #打开窗口
    MainWindow = QtWidgets.QMainWindow()
    MainWindow.resize(300,180)
    MainWindow.setWindowTitle("mytool")
    ui = MainUI()
    ui.setupFunction()
    #设置标签
    lable=QtWidgets.QLabel(MainWindow)
    lable.move(100,20)
    lable.setText("请连续复制单词")
    #若复制错单词可点击按钮进行修改
    btn1=QtWidgets.QPushButton(MainWindow)
    btn1.move(50,120)
    btn1.setText("revise")
    btn1.clicked.connect(button1Clicked)   
    #点击按钮进行翻译
    btn2=QtWidgets.QPushButton(MainWindow)
    btn2.move(150,120)
    btn2.setText("translate")
    btn2.clicked.connect(button2Clicked)   
    #固定模板
    MainWindow.show()
    sys.exit(app.exec_())

限于知识水平,代码风格不够干净简洁。最后运行虚拟环境,安装pyinstaller(导入的模块应该尽可能的少),通过pyinstaller进行打包生成exe文件。

遇到的问题

1.PyQt5的安装 link
2.vs code 配置python虚拟环境 link
创建虚拟环境(virtualenv --system-site-packages 文件夹)
进入虚拟环境( for windows)虚拟环境\Scripts\activate
退出虚拟环境 deactivate
3.在虚拟环境运行python的两条途径

  1. 点击vs code页面右上方的的三角形按钮在虚拟环境运行程序
  2. cmd进入scripts文件夹,activate即可在虚拟环境运行程序

4.PyQt5实现把剪切板内容显示在GUI上的尝试

  1. 通过sys.stdout link
  2. 试图通过QTread绕开死循环的坑 link
  3. 通过Qclipboard.dataChanged()解决 link

5.关于Qclipboard的使用 link
6.文件的读取和清空link
7.打包问题TypeError: an integer is required link
8.以(“r+” “rb+” “w” “wb” “wb+”)方式打开文件,truncate()失效,
原因在于lines = f.read().splitlines()

Reference

1.面向对象的编程,线程和进程link
2.learn python the hard way
3.Automate the Boring Stuff with Python(pyperclip,requests, webbrowser, bs4,os,subprocess模块的使用)
4.PyQt5 link
link
5.翻译 credit to 有道词典

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值