跳到正文

个人记录

Python小项目:单词测试(更新到1.1版本)

AlexNotFoundBNDS约 25 分钟
原文
文章信息与版本

文章信息

发布
2022年12月5日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 25 分钟

版本

  1. v1当前

功能

英文命令行界面

通过读入Excel文档来进行单词测试

可以中译英或英译中

可以把常用的Excel文档加入List中,方便读入

命令有help, read, list, test, randomtest, exit, quit

具体功能输入help命令进行查看

使用须知

环境要求

需要Python3环境

如果没有安装openpyxl模块,请打开命令行并输入pip install openpyxl进行安装

使用准备

将后文源码粘贴到本地Python文档中,并在此文档的目录下创建两个文档:

一个是WorkbookList.xlsx,内容留空,用于存放List

一个是help.txt,内容粘贴后文源码后面的help.txt

表格要求

读入的表格只能A列和B列有文字

A列英文单词,B列中文释义

可以在A列放入词组/句子进行翻译

更新日志(英)

代码
Vocabulary Test Program by AlexNotFoundBNDS

version list and new options:
    2022/11/12 19:53 0.1
        only have read, show and ordered test function
    2022/11/12 20:30 0.2
        add random test function
    2022/11/13 09:58 0.3
        the excel of the vocabularies list should be input
        so that users can choose which excel the program would read
    2022/11/16 02:49 0.3.1
        add "> " before commands users input
        make it more pleasing to the eye
    2022/11/16 22:46 0.4
        add List function
        user can read the Excel in the List with it's "name"
        so they wouldn't have to input the whole path every time they read an Excel
        user can use listshow to know which Excel is in the List
    2022/11/23 16:46 0.5
        add listedit & listdel function
        user can use listedit to append or edit the Excel in the List
        and they can use listdel to delete the Excel in the List
    2022/12/03 14:30 0.6
        add parameter system, make it be more like a commandline
        put listshow, listedit, listdel together
        put read, readfromlist together, change readfromlist into read list
    2022/12/05 20:36 1.0
        add help function and parameter to show how to use each command
    2022/12/26 21:28 1.1
        fixed bug about invalid secondary reading from List

源码

Python
from openpyxl import load_workbook
from openpyxl import Workbook
import random
version = "1.1"
wb = Workbook()
ws = wb.active
WorkbookList = load_workbook("WorkbookList.xlsx")
List = WorkbookList.active
Lists = {}
path = ""
English = []
Chinese = []
help = {}


def readhelp():
    file = open("help.txt", "r")
    tmp = 0
    a = ""
    b = ""
    for line in file.readlines():
        if tmp == 0:
            a = line
            tmp = 1
        elif line == "\n":
            help[a] = b
            a = ""
            b = ""
            tmp = 0
        elif tmp == 1:
            b += line
    help[a] = b+"\n"
    file.close()


def read():     # read vocabularies from the excel
    global wb, ws, English, Chinese, path
    English = []
    Chinese = []
    print("Please input the full path of the excel:")
    path = input()
    wb = load_workbook(path)
    ws = wb.active
    while ws['A' + str(len(English)+1)].value is not None:
        English.append(ws['A' + str(len(English)+1)].value)
        Chinese.append(ws['B' + str(len(Chinese)+1)].value)
    print("Finished!")
    print("Current file:", path)
    print(str(len(English))+" Vocabularies")


def readlist():
    global List, Lists
    while List['A' + str(len(Lists)+1)].value is not None:
        Lists[List['A' + str(len(Lists)+1)].value] = List['B' + str(len(Lists)+1)].value


def readfromlist():
    global wb, ws, English, Chinese, path, Lists
    print("Please input the name of the vocabulary list:")
    name = input()
    path = Lists[name]
    wb = load_workbook(path)
    ws = wb.active
    English = []
    Chinese = []
    while ws['A' + str(len(English) + 1)].value is not None:
        English.append(ws['A' + str(len(English) + 1)].value)
        Chinese.append(ws['B' + str(len(Chinese) + 1)].value)
    print("Finished!")
    print("Current List Name:", name)
    print(str(len(English)) + " Vocabularies")


def listshow():
    global Lists
    for i in Lists.keys():
        print(i, ":", Lists[i])


def listedit():
    global Lists
    print("Please input the name of the list:")
    name = input()
    print("Please input the full path of the Excel:")
    path1 = input()
    Lists[name] = path1
    print("Edit Success!")
    savelist()


def listdel():
    global Lists
    print("Please input the name of the list you want to delete")
    name = input()
    if name not in Lists:
        print("Error: Name isn't in the Lists!")
        return
    del Lists[name]
    print("Delete Finished!")
    savelist()


def savelist():
    global List, Lists, WorkbookList
    tmp = []
    while List['A' + str(len(Lists) + 1)].value is not None:
        Lists[List['A' + str(len(Lists) + 1)].value] = List['B' + str(len(Lists) + 1)].value
    WorkbookList = Workbook()
    List = WorkbookList.active
    for i in Lists.keys():
        tmp.append(i)
    for i in range(1, len(Lists)+1):
        List['A'+str(i)] = tmp[i-1]
        List['B'+str(i)] = Lists[tmp[i-1]]
    WorkbookList.save("WorkbookList.xlsx")


def show():     # print the vocabularies from "English" and "Chinese"
    for i in range(len(English)):
        print(English[i], Chinese[i])


def test(mode):     # start an ordered test
    correct = 0
    wrong = 0
    wrong_chinese = []
    wrong_english = []
    if mode == 'C':     # Chinese to English
        print("\nChinese to English Vocabulary Test", end='\n\n')
        for i in range(len(English)):
            print(Chinese[i])
            ans = input()
            if ans == English[i]:
                print("Correct!", end='\n\n')
                correct += 1
            else:
                print("Wrong! The correct answer is:", English[i], end='\n\n')
                wrong += 1
                wrong_english.append(English[i])
                wrong_chinese.append(Chinese[i])
    if mode == 'E':     # English to Chinese
        print("\nEnglish to Chinese Vocabulary Test", end='\n\n')
        for i in range(len(English)):
            print(English[i])
            ans = input()
            if ans == Chinese[i]:
                print("Correct!")
                correct += 1
            else:
                print("Wrong! The correct answer is:", Chinese[i], end='\n\n')
                wrong += 1
                wrong_english.append(English[i])
                wrong_chinese.append(Chinese[i])
    print("The test is over!")
    print("All:", len(Chinese))
    print("Correct:", correct)
    print("Wrong:", wrong)
    print("Accuracy:", str(correct/len(Chinese)*100)+"%", end="\n\n")
    print("Wrong Vocabulary List:")
    for i in range(wrong):
        print(wrong_chinese[i], wrong_english[i])
    print("")


def randomtest(mode):     # start a random ordered test
    correct = 0
    wrong = 0
    order = []
    for i in range(len(English)):
        order.append(i)
    random.shuffle(order)       # shuffle the order of vocabularies
    wrong_chinese = []
    wrong_english = []
    if mode == 'C':     # Chinese to English
        print("\nChinese to English Vocabulary Random Test", end='\n\n')
        for i in order:
            print(Chinese[i])
            ans = input()
            if ans == English[i]:
                print("Correct!", end='\n\n')
                correct += 1
            else:
                print("Wrong! The correct answer is:", English[i], end='\n\n')
                wrong += 1
                wrong_english.append(English[i])
                wrong_chinese.append(Chinese[i])
    if mode == 'E':     # English to Chinese
        print("\nEnglish to Chinese Vocabulary Random Test", end='\n\n')
        for i in order:
            print(English[i])
            ans = input()
            if ans == Chinese[i]:
                print("Correct!", end='\n\n')
                correct += 1
            else:
                print("Wrong! The correct answer is:", Chinese[i], end='\n\n')
                wrong += 1
                wrong_english.append(English[i])
                wrong_chinese.append(Chinese[i])
    print("The test is over!")
    print("All:", len(Chinese))
    print("Correct:", correct)
    print("Wrong:", wrong)
    print("Accuracy:", str(correct / len(Chinese) * 100) + "%", end="\n\n")
    print("Wrong Vocabulary List:")
    for i in range(wrong):
        print(wrong_chinese[i], wrong_english[i])
    print("")


def main():
    print("Vocabulary Testing Program "+version)
    print("by AlexNotFoundBNDS")
    print('press "help" to learn how to use each command.')
    readlist()
    readhelp()
    while True:
        print(">", end=' ')
        a = input()
        para = a.split(" ")
        if para[0] == "help":
            if len(para) == 1:
                for i in help.keys():
                    print(i + help[i], end="")
            elif para[1]+"\n" in help.keys():
                print(help[para[1]+"\n"])
            else:
                print("Cannot find command:", para[1])
        elif para[0] == "read":
            if len(para) == 1:
                read()
            elif len(para) != 2:
                print("To Many Parameter!")
            elif para[1] == "help":
                print(help[para[0]+"\n"])
            elif para[1] == "list":
                readfromlist()
        elif para[0] == "list":
            if len(para) != 2:
                print("Missing Parameter or To Many Parameter!")
            elif para[1] == "help":
                print(help[para[0]+"\n"])
            elif para[1] == "show":
                listshow()
            elif para[1] == "edit":
                listedit()
            elif para[1] == "del":
                listdel()
        elif para[0] == "exit" or para[0] == "quit":
            if len(para) == 1:
                print("Bye Bye! Press enter to exit.")
                input()
            elif para[1] == "help":
                print(help[para[0]+"\n"])
            else:
                print("Wrong Parameter!")
            break
        elif para[0] == "show":
            if len(para) == 1:
                if path == "":
                    print("Missing file! Please read an Excel or a list first.")
                show()
            elif para[1] == "help":
                print(help[para[0]+"\n"])
            else:
                print("Wrong Parameter!")
        elif para[0] == "test":
            if len(para) != 2:
                print("Missing Parameter or To Many Parameter!")
            elif para[1] == "help":
                print(help[para[0]+"\n"])
            elif path == "":
                print("Missing file! Please read an Excel or a list first.")
            elif para[1].upper() == "C":
                test("C")
            elif para[1].upper() == "E":
                test("E")
            else:
                print("Wrong Parameter!")
        elif para[0] == "randomtest":
            if len(para) != 2:
                print("Missing Parameter or To Many Parameter!")
            elif para[1] == "help":
                print(help[para[0]+"\n"])
            elif path == "":
                print("Missing file! Please read an Excel or a list first.")
            elif para[1].upper() == "C":
                randomtest("C")
            elif para[1].upper() == "E":
                randomtest("E")
            else:
                print("Wrong Parameter!")
        else:
            print("Cannot find command:", para[0])


if __name__ == "__main__":
    main()

help.txt

代码
help
Show how to use each command.
format help [no para] [command] [help]
parameter:
    no para: show all command and it's help.
    command: show this command's help.
    help: show this help.

read
Read an Excel from a full path.
format: read [no para] [help]
parameter:
    no para: read an Excel from a full path.
    help: show this help.

list
Operate with list.
format: list [show] [edit] [del] [help]
parameter:
    show: show all Excel's "name" and full path in the list.
    edit: append or edit an Excel.
    del: delete an Excel.
    help: show this help.

exit
Exit this program. same as command "quit"
format: exit [no para] [help]
parameter:
    no para: exit this program.
    help: show this help.

quit
Exit this program. same as command "exit"
format: quit [no para] [help]
parameter:
    no para: exit this program.
    help: show this help.

show
Show all vocabularies with it's Chinese meanings from the Excel which was opened
format: show [no para] [help]
parameter:
    no para: show all vocabularies.
    help: show this help.

test
Test the words in Excel in it's own order.
format: test [c/C] [e/E] [show]
parameter:
    c/C: test Chinese-to-English.
    e/E: test English-to-Chinese.
    help: show this help.

randomtest
Test the words in Excel in random order.
format: test [c/C] [e/E] [show]
parameter:
    c/C: test Chinese-to-English.
    e/E: test English-to-Chinese.
    help: show this help.
原文
抓取于
  1. abv3Rpkg

    6