【问题标题】:Python Vocab CheckerPython 词汇检查器
【发布时间】:2013-05-08 01:59:44
【问题描述】:

我正在寻找一个基于 Python 的词汇检查器,供我的小表弟用来学习。该程序的目的是显示一个单词,然后她需要输入定义并检查它。我想知道最好的方法是使用数组列表:

vocab = ['Python','OSX']
definition = ['programming language','operating system']

这是解决此问题的最佳方法吗?如果是这样,我如何让程序随机显示一个词汇,然后检查定义。任何帮助将不胜感激。谢谢各位。

好的。所以这就是我到目前为止所拥有的...... #俄语翻译项目

import os
import random

#Asks users if they want to add more vocabulary
word_adder=raw_input("Add more words? If yes, press 1: ")
with open("Russian_study.txt","a") as f:
while word_adder=="1":
    word=raw_input("Enter word: ")
    translation=raw_input("Word translation: ")
    f.write("'{0}':{1},".format(word,translation))
    word_adder=raw_input("Add another word? If yes, press 1: ")

#Checks to see if file exists, if not one is created
with open("Russian_study.txt","a") as f:
pass

os.system('clear')
print("Begin Quiz")

#Begin testing user
with open("Russian_study.txt","r") as f:
from random import choice
question = choice(list(f))
result = raw_input('{0} is '.format(question))
print('Correct' if result==f[question] else ':(')

但是,我的输出是

Begin Quiz
'Один':'One', is 

如何让它只显示Один并检查用户输入?

【问题讨论】:

  • 您可能更喜欢dict 映射而不是一对列表

标签: python vocabulary


【解决方案1】:

使用字典:

d={'Python':'programming language', 'OSX':'operating system'}

from random import choice
q = choice(list(d))
res = input('{0} is:'.format(q))
print('yay!' if res == d[q] else ':(')

[如果您使用的是python raw_input()而不是input()]

从文件中写入/读取的最简单(但不安全!)方法:

with open('questions.txt', 'w') as f:
    f.write(repr(d))

'questions.txt' 会有这一行:

`{'Python':'programming language', 'OSX':'operating system'}`

所以你可以阅读它

with open('questions.txt') as f:
    q=eval(f.read())

现在 q 和 d 相等。不要将此方法用于“真实”代码,因为“questions.txt”可能包含恶意代码。

【讨论】:

  • 作为附加功能,您可能会尝试规范化输入。例如,最后一行可以是print('yay!' if res.strip().lower() == d[q] else ':(') 等等,还有其他方式使它更易于使用
  • 谢谢。如果我要将字典放在文本文件中,它将如何在文件中格式化。
  • 我编辑来读写一个文件。如果您想对其进行格式化,请查看文档中的format
【解决方案2】:

1) 您可以使用 random.choice() 从您的词汇列表(或字典的 keys())中随机选择一个元素。

2) 确定答案何时足够接近定义是比较棘手的。您可以简单地在答案字符串中搜索某些关键词。或者如果你想变得更复杂,你可以计算两个字符串之间的 Levenshtein 距离。您可以在此处阅读有关 L 距离的信息:http://en.wikipedia.org/wiki/Levenshtein%5Fdistance。并且网上有计算L距离的python菜谱。

【讨论】:

  • 如果它只是一个学习辅助工具,而不是用来给某人评分,那么在你输入你的定义后显示就足够了。然后学生可以自己决定他们有多接近。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 2019-01-23
  • 1970-01-01
  • 2020-12-07
  • 1970-01-01
  • 1970-01-01
  • 2017-04-01
相关资源
最近更新 更多