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

2024-04-26 06:49:42 发布

您现在位置: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类型


Tags: 文件orgidhttpurl密码doctitle
1条回答
网友
1楼 · 发布于 2024-04-26 06:49:42

不要用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

相关问题 更多 >