用Python写一个用来背单词的程序
在运行该程序前,需要将一个名为“word_list.xlsx”文件放在与代码同一个路径下。xlsx文件格式如下:

代码如下:
import pandas as pd
import random
# 加载Excel文件
def load_excel(file):
return pd.read_excel(file, sheet_name=None)
# 列出所有的sheet名字
def list_sheets(data):
sheets = data.keys()
for sheet in sheets:
print(sheet)
# 选择需要背诵的sheet
def select_sheet(data):
sheet_name = input("请输入需要背诵的sheet名字:")
if sheet_name in data:
words = data[sheet_name]
# 将词意列的数据转换为字符串类型
words['词意'] = words['词意'].astype(str)
# 获取单词和词意列的数据
word_list = [(word, meaning) for word, meaning in zip(words['单词'], words['词意'])]
# 随机选取单词
random.shuffle(word_list)
correct_words = []
incorrect_words = word_list.copy()
while incorrect_words:
word, meaning = incorrect_words.pop(0)
print("单词:", word)
user_meaning = input("请输入词意:")
if user_meaning.strip().lower() == meaning.strip().lower():
print("回答正确!")
correct_words.append((word, meaning))
else:
print("回答错误!正确的词意是:", meaning)
input("按Enter显示下一个单词")
random.shuffle(incorrect_words)
print("所有单词都已经背诵完毕")
if correct_words:
print("背诵正确的单词及对应词意:")
correct_df = pd.DataFrame(correct_words, columns=['单词', '词意'])
print(correct_df)
else:
print("没有背诵正确的单词")
print("背诵错误的记录:")
incorrect_df = pd.DataFrame(word_list, columns=['单词', '词意']).drop(correct_df.index, errors='ignore')
print(incorrect_df)
else:
print("无效的sheet名字")
# 主选项页面
def main_menu(data):
while True:
print("\n主选项页面:")
print("1. 查看sheet")
print("2. 选择需要背诵的sheet")
print("3. 退出程序")
choice = input("请输入选项:")
if choice == "1":
list_sheets(data)
elif choice == "2":
select_sheet(data)
elif choice == "3":
break
else:
print("无效的选项")
# 加载Excel文件
data = load_excel("word_list.xlsx")
# 运行程序
main_menu(data)

浙公网安备 33010602011771号