吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 4818|回复: 26
收起左侧

[Python 转载] 自助单词听写

[复制链接]
Lthero 发表于 2020-12-7 14:32
初学python不久,尝试写能播报英文单词的代码

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

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

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


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



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


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


未经本人允许禁止转载!

[Python] 纯文本查看 复制代码
# -*- 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'][0][0]['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[res] = 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[0])

    # 优先从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[0])
                if len(lst_wrong) > 0 and total > 0:
                    lst_pri.append(line[0])
                    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[0]] = line[2]

    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[word] + '\n')


if __name__ == '__main__':
    total = eval(input('想要听写单词数目 '))
    start()
QQ截图20201207140845.png
QQ截图20201207140949.png

免费评分

参与人数 5吾爱币 +9 热心值 +4 收起 理由
programdog + 1 用心讨论,共获提升!
1472 + 1 我很赞同!
苏紫方璇 + 7 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
隐而远外 + 1 好厉害,持续关注!
iuhgnor + 1 + 1 谢谢@Thanks!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

 楼主| Lthero 发表于 2020-12-7 14:57
帖子不能再编辑,这里补充一下,需要另外安装 playsound 模块
 楼主| Lthero 发表于 2020-12-7 18:21
用于测试的单词库,我选了一些四级单词

words.txt

25.19 KB, 下载次数: 34, 下载积分: 吾爱币 -1 CB

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

修改了原代码

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

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

要安装pyttsx3库

pip install pyttsx3

现在word.txt可以直接输入中文,还是一个单词一行
[Python] 纯文本查看 复制代码
# -*- 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[res] = ''
        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[0])

    # 优先从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[0])
                if len(lst_wrong) > 0 and total > 0:
                    lst_pri.append(line[0])
                    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[0]] = line[2]

    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[word] + '\n')


if __name__ == '__main__':
    total = eval(input('想要听写单词数目 '))
    start()
xMan1973 发表于 2021-9-23 10:11
运行报错如下,怎么回事呢?谢谢。

Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] 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[driverName]
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\weakref.py", line 137, in __getitem__
    o = self.data[key]()
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[level:], 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
人才啊,厉害了
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-11-25 11:25

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表