【问题标题】:How to create specific python dictionaries with files如何使用文件创建特定的 python 字典
【发布时间】:2021-07-08 21:37:57
【问题描述】:

我正在尝试使用字典和文件通过 Python 创建一个词汇测验。我有两个单独的 .txt 文件,包含 10 个不同的单词,格式如下:

图书馆:la biblioteca
学校: el colegio, la escuela

运行:correr
搜索:mirar, buscar

然后我让我的用户选择他们想要被测验的 .txt 文件以及他们想要被测验的单词数。 如何创建一个以英语单词为键、以相应的西班牙语单词为值的字典?我还需要根据用户输入的数字随机选择单词


我现在的代码是这样的:(第一个函数(dict_places)将被复制到第二个txt文件(dict_verbs))

def dict_places():
    f = open("places.txt")
    vocab_dict = {}
    for line in f:
        if line.strip():
            key, val = line.split(":")
        vocab_dict[key] = val.split()
        print(vocab_dict)

def main():
    file = input("Please choose one of the following files:\n verbs.txt \n places.txt\nPlease make your choice: ")
    if file == "places.txt":
        print("10 entries found,")
        entries = int(input("How many entries would you like to be quizzed on? "))
        dict_places(entries)
    if file == "verbs.txt":
        print("10 entries found,")
        entries = int(input("How many entries would you like to be quizzed on? "))
        dict_verbs(entries)

显然,我被困住了。任何帮助将不胜感激:)

【问题讨论】:

  • .readlines().split(': ')
  • "我如何创建一个以英语单词为键、相应的西班牙语单词为值的字典?"那么,告诉您英文单词在给定行中的位置的规则是什么?什么规则告诉你西班牙语单词是什么 - 特别是告诉你如何分隔单词的规则是什么?鉴于这些规则,你能看到如何从文件的一行中获取字典的键和值吗?鉴于这种能力,您能否通过一次查看文件来了解如何构建字典?你知道如何一次看一行文件吗?
  • "我现在的代码是这样的" 那么,当你尝试代码时会发生什么?离解决问题还有多远?在您自己的评估中,还有哪些步骤可以解决问题,哪些部分您无法弄清楚?

标签: python file dictionary


【解决方案1】:
def dict_places():
    f = open("places.txt")
    vocab_dict = {}
    for line in f:
        if line.strip():
            key, val = line.split(": ")
            vocab_dict[key] = val.strip().split(", ")

    print(vocab_dict)

【讨论】:

    猜你喜欢
    • 2014-03-19
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 2021-03-25
    • 1970-01-01
    相关资源
    最近更新 更多