[英]Trying to read a single column text file by two's to make a key-value pair in a dictionary
Working on a typical Python project of quizzing a user on state's capitals.从事一个典型的 Python 项目,对用户进行州首府的测验。 Instead of just copying and creating my own dictionary I'm reading a text file.
我正在阅读一个文本文件,而不仅仅是复制和创建我自己的字典。 I have the portion of the quiz set up(I think) and I'm struggling with creating the actual key-value pairs.
我已经设置了测验的一部分(我认为)并且我正在努力创建实际的键值对。 The text file looks like this:
文本文件如下所示:
Alabama阿拉巴马州
Montgomery蒙哥马利
Alaska阿拉斯加州
Juneau朱诺
Arizona亚利桑那
Phoenix凤凰
Arkansas阿肯色州
Little Rock etc....小石城等……
I can't figure out how to read the first line as the key(state) and second line as the value(capital).我不知道如何将第一行读取为键(状态),将第二行读取为值(大写)。 Once I have the correct variables I will change what my main method calls.
一旦我有了正确的变量,我将改变我的主要方法调用的内容。 Any help or feedback is appreciated.
任何帮助或反馈表示赞赏。 Thanks!
谢谢!
Here is my code:这是我的代码:
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()
I would suggest reading the file as a string then do this我建议将文件作为字符串读取然后执行此操作
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.