简体   繁体   English

Python-从多个文本文件读入字典

[英]Python- Reading from multiple text files into dictionary

I'm trying to combine two files into a dictionary. 我正在尝试将两个文件合并成一个字典。 They are both text files. 它们都是文本文件。

The first file has the state initials and population. 第一个文件具有状态缩写和填充。 It looks like this: 看起来像这样:

AL 4447100
AK 626932
AZ 5130632
AR 2673400
CA 33871648
CO 4301261
...

The second file has the state initial and state name (this time per line, not side by side): 第二个文件具有状态初始名称和状态名称(这次是每行一次,而不是并排):

AL
Alabama
AK
Alaska
AZ
Arizona
AR
Arkansas
CA
California
CO
Colorado
...

I'm trying to create a dictionary that looks like this 我正在尝试创建一个像这样的字典

{'Alabama': 4447100, 'Alaska': 626932, ...}

Now, I'm having trouble reading the first text file. 现在,我在读取第一个文本文件时遇到了麻烦。 How do I read just the numbers when the abbreviations are in the way? 缩略语出现时,如何只读数字?

The second text file is easier as I can read every other line. 第二个文本文件比较容易,因为我可以每隔一行读一次。

Any suggestions? 有什么建议么?

You can use split depending on how you've read the data in. 您可以根据读取数据的方式使用拆分

For example: 例如:

>>> myStr = 'AL 4447100'
>>> myStr.split(' ')
>>> ['AL', '447100']

I won't give a full solution since this may be homework but your final one should have some code like this 由于这可能是家庭作业,因此我不会给出完整的解决方案,但是您的最后一个应该有一些这样的代码

d = {}

with open('file1.txt') as f:
    for line in f:
         state, pop = line.split()
         d[states[state]] = int(pop) # states is a dictionary with initials as 
                                     # the  keys and full names as values

Q) Now, I'm having trouble reading the first text file. 问)现在,我在读取第一个文本文件时遇到了麻烦。 How do I read just the numbers when the abbreviations are in the way? 缩略语出现时,如何只读数字?

A) You can use this with a string of each line to strip the first 3 characters from the string (acronym and a space): A)您可以将其与每行的字符串一起使用,以从字符串中去除前3个字符(缩写和空格):

number = lineString[3:]

Assuming you have files states.txt and pop.txt 假设您有文件states.txtpop.txt

with open("states.txt") as f1:
   x= f1.read().split()
   states = {state:abrv for state,abrv in zip(x[0::2],x[1::2])}

with open("pop.txt") as f2:
   y= f2.read().split()
   pop = {states[abrv]:val for abrv,val in zip(y[0::2],y[1::2])}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM