Lthero 发表于 2020-12-7 14:32

自助单词听写

初学python不久,尝试写能播报英文单词的代码

功能:实现语音播报单词库中英文单词。

可以模拟上课老师听写,或用于自学新单词

可以自定义单词库,默认单词库是四级的一些单词,在words.txt中,可以增添删改,但最好保持一行只有一个单词(可以只有英文)


语音的播放是来自有道词典的美式发音音频,音频会自动下载到电脑中,保存位置在word_sound文件夹中



代码如下,程序打包成exe我这边有点问题,后续可能会更新


本人编程菜鸟,欢迎各位大佬帮助纠正!!


未经本人允许禁止转载!

# -*- encoding=utf8 -*-
__author__ = 'lthero'

import os
import random as ra
import json
import requests
import time
# 声音播放
from playsound import playsound

lst = []
lst_wrong = []
lst_success = {}
lst_pri = []

# 英文翻译
def translate(sec):
    url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
    data = {}
    data['i'] = sec
    data['from'] = 'en'
    data['to'] = 'zh-CHS'
    data['doctype'] = 'json'
    data = requests.get(url, data)
    content = data.content
    res = json.loads(content)
    translation = res['translateResult']['tgt']
    return translation


# 下载音频
def down_mp3(word):
    url = 'http://dict.youdao.com/dictvoice?type=0&audio=' + word
    html = requests.get(url)
    file_name = 'words_sound'
    if not os.path.isdir(file_name):
      os.mkdir(file_name)
    if not os.path.isfile('%s\\audio_%s.mp3' % (file_name, word)):
      with open('%s\\audio_%s.mp3' % (file_name, word), 'wb') as f:
            f.write(html.content)

# 播放声音
def play(word):
    down_mp3(word)
    playsound('words_sound\\audio_%s.mp3' % word)


# 主要功能
def read():
    play('begin')
    already = []
    for i in range(0, total):
      te = ra.choice(lst)
      if te not in lst_success:
            lst_pri.append(te)
    for res in lst_pri:
      if res not in already:
            print('拼写', end=' ')
            already.append(res)
            play(res)
            time.sleep(0.8)
            play(res)
            come = input('')
            trans = translate(res)
            wrong_time = 0
            while come != res:
                print('再尝试拼写', end=' ')
                play(res)
                come = input('')
                wrong_time += 1
                if wrong_time == 2:
                  print('需要多练习! %-15s %-5s' % (res, trans))
                  lst_wrong.append(res)
                  break
            else:
                print('已经掌握了! %-15s %-5s' % (res, trans))
                if res in lst_wrong:
                  lst_wrong.remove(res)
                lst_success = trans
      else:
            continue
    play('end')


def start():
    global total
    print('音频会读两遍,拼写正确则继续.错误则重复读,共2次可再输入机会')
    with open('words.txt', 'r', encoding='utf-8') as f:
      for line in f.readlines():
            line = line.replace('/', ' ')
            line = line.strip('\n .0123456789\t').split(' ')
            lst.append(line)

    # 优先从fail中选中听写
    if os.path.isfile('words_fail.txt'):
      with open('words_fail.txt', 'r') as f:
            for line in f.readlines():
                line = line.strip('\n').split(' ')
                lst_wrong.append(line)
                if len(lst_wrong) > 0 and total > 0:
                  lst_pri.append(line)
                  total -= 1

    # 读取已经通关的单词
    if os.path.isfile('words_success.txt'):
      with open('words_success.txt', 'r', encoding='utf-8') as f:
            for line in f.readlines():
                line = line.strip('\n').split(' ')
                lst_success] = line

    read()
    save()


def save():
    with open('words_fail.txt', 'w', encoding='utf-8')as f:
      for line in lst_wrong:
            f.write(line + '\n')
    with open('words_success.txt', 'w', encoding='utf-8')as f:
      for word in lst_success:
            f.write(word + "" + lst_success + '\n')


if __name__ == '__main__':
    total = eval(input('想要听写单词数目 '))
    start()

Lthero 发表于 2020-12-7 14:57

帖子不能再编辑,这里补充一下,需要另外安装 playsound 模块

Lthero 发表于 2020-12-7 18:21

用于测试的单词库,我选了一些四级单词

Lthero 发表于 2020-12-16 22:52

alam-132 发表于 2020-12-16 13:52
楼主威武。我想要做一个小学生听写生字生词的,是不是只需要把你这个单词表(word.txt)改成生字表就行了? ...

修改了原代码

我听了下有道中文语音,读音并不是很准。

现在用机器读音代替,用的是普通话,准确度很高,可以满足听写需求

要安装pyttsx3库

pip install pyttsx3

现在word.txt可以直接输入中文,还是一个单词一行
# -*- encoding=utf8 -*-
__author__ = 'lthero'
import os
import random as ra
import time
import pyttsx3

def play(msg):
    engine = pyttsx3.init()
    rate = engine.getProperty('rate')
    engine.setProperty('rate', rate - 50)
    volume = engine.getProperty('volume')
    voices = engine.setProperty(
          'voice', "com.apple.speech.synthesis.voice.ting-ting.premium")
    engine.setProperty('voice', voices)
    engine.setProperty('volume', 0.8)
    engine.say(msg)
    engine.runAndWait()
    engine.stop()

lst = []
lst_wrong = []
lst_success = {}
lst_pri = []


# 主要功能
def read():
    already = []
    for i in range(0, total):
      te = ra.choice(lst)
      if te not in lst_success:
            lst_pri.append(te)
    for res in lst_pri:
      if res not in already:
            print('拼写', end=' ')
            already.append(res)
            play(res)
            time.sleep(0.8)
            play(res)
            come = input('')
            wrong_time = 0
            while come != res:
                print('再尝试拼写', end=' ')
                play(res)
                come = input('')
                wrong_time += 1
                if wrong_time == 2:
                  print('需要多练习! %-15s' % res)
                  lst_wrong.append(res)
                  break
            else:
                print('已经掌握了! %-15s' % res)
                if res in lst_wrong:
                  lst_wrong.remove(res)
                lst_success = ''
      else:
            continue


def start():
    global total
    print('音频会读两遍,拼写正确则继续.错误则重复读,共2次可再输入机会')
    with open('words.txt', 'r', encoding='utf-8') as f:
      for line in f.readlines():
            line = line.replace('/', ' ')
            line = line.strip('\n .0123456789\t').split(' ')
            lst.append(line)

    # 优先从fail中选中听写
    if os.path.isfile('words_fail.txt'):
      with open('words_fail.txt', 'r',encoding='utf-8') as f:
            for line in f.readlines():
                line = line.strip('\n').split(' ')
                lst_wrong.append(line)
                if len(lst_wrong) > 0 and total > 0:
                  lst_pri.append(line)
                  total -= 1

    # 读取已经通关的单词
    if os.path.isfile('words_success.txt'):
      with open('words_success.txt', 'r', encoding='utf-8') as f:
            for line in f.readlines():
                line = line.strip('\n').split(' ')
                lst_success] = line

    read()
    save()


def save():
    with open('words_fail.txt', 'w', encoding='utf-8')as f:
      for line in lst_wrong:
            f.write(line + '\n')
    with open('words_success.txt', 'w', encoding='utf-8')as f:
      for word in lst_success:
            f.write(word + "" + lst_success + '\n')


if __name__ == '__main__':
    total = eval(input('想要听写单词数目 '))
    start()

xMan1973 发表于 2021-9-23 10:11

运行报错如下,怎么回事呢?谢谢。

Python 3.7.4 (tags/v3.7.4:e09359112e, Jul8 2019, 20:34:20) on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
RESTART: C:/Users/Administrator/AppData/Local/Programs/Python/Python37/words.py
想要听写单词数目 5
音频会读两遍,拼写正确则继续.错误则重复读,共2次可再输入机会
拼写 Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\pyttsx3\__init__.py", line 20, in init
    eng = _activeEngines
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\weakref.py", line 137, in __getitem__
    o = self.data()
KeyError: None

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:/Users/Administrator/AppData/Local/Programs/Python/Python37/words.py", line 102, in <module>
    start()
File "C:/Users/Administrator/AppData/Local/Programs/Python/Python37/words.py", line 87, in start
    read()
File "C:/Users/Administrator/AppData/Local/Programs/Python/Python37/words.py", line 38, in read
    play(res)
File "C:/Users/Administrator/AppData/Local/Programs/Python/Python37/words.py", line 9, in play
    engine = pyttsx3.init()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\pyttsx3\__init__.py", line 22, in init
    eng = Engine(driverName, debug)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\pyttsx3\engine.py", line 30, in __init__
    self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\pyttsx3\driver.py", line 50, in __init__
    self._module = importlib.import_module(name)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name, package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\pyttsx3\drivers\sapi5.py", line 10, in <module>
    import pythoncom
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\pythoncom.py", line 2, in <module>
    import pywintypes
ModuleNotFoundError: No module named 'pywintypes'

zhang1497 发表于 2020-12-7 14:38

厉害,谢谢分享

zt185 发表于 2020-12-7 14:41

楼主真牛这也能想得出来,支持!

我姓张嚣张的张 发表于 2020-12-7 14:43

英语是我永远的痛啊,感谢分享

Lthero 发表于 2020-12-7 14:46

我姓张嚣张的张 发表于 2020-12-7 14:43
英语是我永远的痛啊,感谢分享

我也是啊,好久没学过认真英语了,昨天背单词时(老师要听写)突然想到的写个小程序,效果还不错

qq9953 发表于 2020-12-7 14:48

值得学习,期待成品!

cocoan 发表于 2020-12-7 14:52

很实用的应用,赞!

Ricky_Xiao 发表于 2020-12-7 14:54

厉害了,佩服。

Zimin 发表于 2020-12-7 15:22

人才啊,厉害了
页: [1] 2 3
查看完整版本: 自助单词听写