还在用背单词App?使用Python开发英语单词自测工具,助你逆
2019-09-26 本文已影响0人
9ba4bd5525b9
需求分析
既然上面说了那么多的怀旧梗,那今天就仿照着从前的方式,做一个稍微高端一些的单词自测工具。
先来看看实现效果吧…程序输入你想测试的单词数量,然后系统自动生成html测试题,之后你就可以通过速记与查看来检测哪些单词你没记住喽…
在这里插入图片描述
找单词
背单词我们得先有单词吧?从百度找了一篇2019cet4英语单词表!
在这里插入图片描述
左图下载的word文档的内容包含各种广告,为了方便,我直接把它全部拷贝存在文本文档中,类似右图。
观察保存的文本内容,我们可以通过 斜杠’/‘
生成测试题
我们准备好了试题,怎么生成测试题呢?之前学习excel读写的时候,写过一篇英语单词自测的文章:
在这里插入图片描述
先生成单词音标,然后用户输入翻译,最后再D列追加正确的翻译…
最近没怎么学习web端的知识,所以今天我们来写一套自动生成html测试题的练习吧!
准备基础html文档root.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>清风Python英语自测工具</title>
<link rel="icon" href="basic/favicon.ico">
<link href="basic/bootstrap.min.css" rel="stylesheet">
<link href="basic/index.css" rel="stylesheet">
<script src="basic/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h3 class="title">清风Python英语单词自测工具</h3>
<table class="table table-striped table-hover">
<thead>
<td>序号</td>
<td>翻译</td>
<td>音标</td>
<td>单词</td>
<td>翻牌</td>
</thead>
<tbody>
{content}
</tbody>
</table>
</div>
</body>
<script>
$("button").click(function() {
var word = $("." + $(this).attr('line'));
if (word.is(':visible')) {
word.slideUp();
} else {
word.slideDown();
}
});
</script>
</html>
其中content的内容,为我们等下自动生成试题…
其中引入的bootstrap、jQuery,都放在代码同级的basic.html文件夹中…
Python代码编写
Python的代码实现起来也比较简单,读取用户测试数量,然后random获取随机测试内容,拆分数据后进行html内容组装,最终生成自测html练习题:
import os
import random
import re
'''
更多Python学习资料以及源码教程资料,可以加群821460695 免费获取
'''
class EnglishWordsTest:
def __init__(self):
self.root_path = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(self.root_path, 'basic', 'cet4.txt'), encoding='utf-8') as f:
_all_words = f.readlines()
self.html = ""
self.clean_data(random.sample(_all_words, text_num))
def clean_data(self, data):
exam_data = list(map(lambda x: re.sub("\s", '', x).split('/'), data))
for num, line in enumerate(exam_data, start=1):
self.html += """
<tr>
<td>{0}</td>
<td>{3}</td>
<td>{2}</td>
<td><div class='word line{0}'>{1}</div></td>
<td><button class='show'line='line{0}'>查看</button></td>
</tr>
""".format(num, *line)
with open(os.path.join(self.root_path, 'basic', 'root.html'), encoding='utf-8') as f:
data = f.read()
with open(os.path.join(self.root_path, 'exam.html'), 'w+', encoding='utf-8') as f:
f.write(data.replace('{content}', self.html))
if __name__ == '__main__':
print("请输入所需测试的单词数量(范围:1-100):")
while True:
try:
text_num = int(input())
if 1 < text_num < 100:
break
except ValueError:
pass
print("请仔细阅读输入范围!")
EnglishWordsTest()