写一个单词背诵的程序实现单词背诵及程序统计
时间: 2023-09-10 11:11:28 浏览: 84
好的,以下是一个 Python 单词背诵程序,它会提示用户输入单词和它的翻译,并将这些单词和翻译保存到文件中。程序还可以统计用户已经背诵的单词数量。
```python
import os
# 单词文件路径
word_file = "words.txt"
# 加载单词列表
def load_words():
words = {}
if os.path.exists(word_file):
with open(word_file, "r") as f:
for line in f:
line = line.strip()
if line:
word, translation = line.split(":")
words[word] = translation
return words
# 保存单词列表
def save_words(words):
with open(word_file, "w") as f:
for word, translation in words.items():
f.write(word + ":" + translation + "\n")
# 添加新单词
def add_word(words):
word = input("请输入新单词:")
translation = input("请输入单词 '" + word + "' 的翻译:")
words[word] = translation
save_words(words)
print("单词 '" + word + "' 已添加。")
# 测试单词
def test_word(words):
if not words:
print("单词列表为空,请先添加单词。")
return
word_count = len(words)
correct_count = 0
for word, translation in words.items():
answer = input("请输入单词 '" + word + "' 的翻译:")
if answer == translation:
print("恭喜你,答对了!")
correct_count += 1
else:
print("很遗憾,答错了。正确答案是 '" + translation + "'。")
print("你总共测试了 " + str(word_count) + " 个单词,其中 " + str(correct_count) + " 个单词回答正确。")
# 主程序
def main():
words = load_words()
while True:
print("请选择操作:")
print("1. 添加新单词")
print("2. 测试单词")
print("3. 统计已背单词数量")
print("4. 退出程序")
choice = input()
if choice == "1":
add_word(words)
elif choice == "2":
test_word(words)
elif choice == "3":
print("你已经背诵了 " + str(len(words)) + " 个单词。")
elif choice == "4":
print("谢谢使用!")
break
else:
print("无效的选择,请重新选择。")
if __name__ == '__main__':
main()
```
这个程序中,我们定义了一个包含若干单词和它们的翻译的字典。程序可以执行添加新单词、测试单词、统计已背单词数量和退出程序等操作。用户添加的单词和翻译会保存到文件中,程序每次启动时会自动加载已保存的单词列表。测试单词时,程序会逐个提示用户输入单词的翻译,并统计回答正确的单词数量。