试图通过二进制读取一个单列文本文件以在字典中创建键值对

问题描述 投票:0回答:1

[一个典型的Python项目,用州府首都查询用户。我正在阅读一个文本文件,而不仅仅是复制和创建自己的字典。我已经完成了部分测验(我认为),并且正在努力创建实际的键值对。文本文件如下所示:

阿拉巴马州

蒙哥马利

阿拉斯加

朱诺

亚利桑那

凤凰

阿肯色州

小石城等等。

我不知道如何读取第一行作为键(状态)和第二行作为值(大写)。一旦有了正确的变量,我将更改主要方法调用的内容。任何帮助或反馈表示赞赏。谢谢!

这是我的代码:

    NUM_STATES = 5

    def make_dictionary():
        with open('state_capitals.txt', 'r') as f:
           d = {}
           for line in f:
               d[line.strip()] = next(f, '').strip()

    def main():
        d = make_dictionary()

        correct = 0
        incorrect = 0

        for count in range(NUM_STATES):
            state, capital = d.popitem()

        print('Enter a capital of ', state, '?', end = '')
        response = input() 
        if response.lower() == capital.lower():
            correct += 1
            print('Correct!')
        else:
             incorrect += 1
             print('Incorrect.')

        print('The number of correct answers is: ', correct)
        print('The number of incorrect answers is: ', incorrect)


    main()
python dictionary text-files
1个回答
0
投票

我建议以字符串形式读取文件,然后执行此操作

with open('state_capitals.txt', 'r') as f:
  file_ = f.read()

file_ = list(filter(lambda x:not x == "", file_.split("\n")))

keys = [key for index,key in enumerate(file_) if index%2 == 0]
values = [value for index,value in enumerate(file_) if not index%2 == 0]

dictionary = dict(zip(keys, values))
print(dictionary)
© www.soinside.com 2019 - 2024. All rights reserved.