如何拆分输入文件的第一行并将它们作为字典存储在 python 中?

How do I split the first line of input file and store them as a dictionary in python?

我的输入文件的第一行如下所示:

<doc id="12" url="http://en.wikipedia.org/wiki?curid=12" title="Anarchism">

我想将它们存储为像这样的键值对 python:

{doc_id: 12, url: http://en.wikipedia.org/wiki?curid=12, title: Anarchism} 

这是我的代码:

infile=open('wiki_00').readline().rstrip()
infile.split()[1:]  

输出如下所示:

['id="12"',
'url="http://en.wikipedia.org/wiki?curid=12"',
'title="Anarchism">']

但我希望删除 "", <> 并将 id 存储为 int 类型

不要 line[1:] 去掉括号。使用 strip 方法:line.strip(' <>') 将从行尾删除所有空格和 <> 字符。

像这样的东西会做我认为你想要的。您可能想要添加错误处理。

def turn_line_into_dict(line):
    # remove the brackets and tag name
    line = line.strip(' <>')
    first_space_idx = line.find(' ')
    line_without_tag = line[first_space_idx+1:]

    attr_list = line_without_tag.split(' ')

    d = {}
    for attr_str in attr_list :
       key,value = attr_str.split('=', 1) # only search for first occurrence, so an '=' in the url doesn't screw this up
       d[key] = value.strip('"\'') # remove quotes and let the dict figure out the type

    return d