简体   繁体   English

从文件读取并将内容转换为字典

[英]Read from a file and turn contents to dictionary

I have a text file with its contents written as follows: 我有一个文本文件,其内容编写如下:

State Texas
Austin
 Houston
 Dallas
State Florida
Orlando
Miami
Jacksonville
Naples
!
State California
San Diego
Los Angeles
San Francisco

Goal: I want to read from this text file and turn them into dictionary and should look like this - 目标:我想从该文本文件中读取并将其转换为字典,并且应该像这样-

state_dict = {
    'Texas': ['Austin', 'Houston', 'Dallas'], 
    'Florida': ['Orlando', 'Miami', 'Jacksonville', 'Naples'], 
    'California': ['San Diego', 'Los Angeles', 'San Francisco']
}

So far my code is this: 到目前为止,我的代码是这样的:

State_Dict = {}
with open('state.txt', 'r') as main_fd:

for mystate in main_fd:
    mystate = mystate.lstrip()

    if ("State" in mystate):
        state_key = "_".join(mystate.split()[1:])
        State_Dict[state_key] = []

        for cities in main_fd:
            if ("!" in cities):
                break

            else:
                State_Dict[state_key].append(cities.rstrip())

print(State_Dict)

But the output is this: 但是输出是这样的:

{
'Texas': [
    ' Austin', ' Houston', ' Dallas', 
    'State Florida', ' Orlando', ' Miami', 
    ' Jacksonville', ' Naples'
    ], 
'California': [
    ' San Diego', ' Los Angeles', ' San Francisco'
    ]
}

How do I fix this? 我该如何解决?

What you are looking for is something like this. 您正在寻找的是这样的东西。 Consider the loop iterating through one line at a time, and build a series of checks for your conditions. 考虑一次循环遍历一行,并针对您的情况进行一系列检查。 PS. PS。 Let me know if this doesn't work, wrote it without testing. 让我知道这是否行不通,未经测试就编写了它。

State_Dict = {}

with open('state.txt', 'r') as main_fd:
    for line in main_fd:
        line = line.strip() #left and right stripped    
        #if ("state" in line.lower()): #better version suggested in comments to handle 'state' and 'State'.
        if ("State" in line):
            state_key = "_".join(line.split()[1:])
            State_Dict[state_key] = []
        elif ("!" in line):
            continue #goes to next iteration of loop instead of stopping the loop unlike break
        else: #assuming last case
            State_Dict[state_key].append(line) #line has already been stripped

print(State_Dict)

The problems with you code were that you were stopping looking for cities of a state when you occurred "!" 您的代码存在的问题是,当您遇到“!”时,您正在停止寻找该州的城市。 but new portion of cities also were indicated by line starting with "State". 但城市的新部分也以“州”开头的线表示。 Another bug was that you iterated for cities from beginning every time instead of state you're currently at. 另一个错误是您每次都从城市开始迭代,而不是从您当前所在的州开始。

State_Dict = {}
main_fd = '''\
State Texas
Austin
Houston
Dallas
State Florida
Orlando
Miami
Jacksonville
Naples
!
State California
San Diego
Los Angeles
San Francisco\
'''.splitlines()

for idx, mystate in enumerate(main_fd):
    if "State" in mystate:
        state_key = "_".join(mystate.split()[1:])
        State_Dict[state_key] = []

        for cities in main_fd[idx+1:]:
            if '!' in cities or "State" in cities:
                break

            else:
                State_Dict[state_key].append(cities.rstrip())

print(State_Dict)

output: 输出:

{'Florida': ['Orlando', 'Miami', 'Jacksonville', 'Naples'], 
'California': ['San Diego', 'Los Angeles', 'San Francisco'], 
'Texas': ['Austin', 'Houston', 'Dallas']}

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

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