简体   繁体   English

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

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

The first line of my input file looks like this:我的输入文件的第一行如下所示:

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

I want store them as key-value pair like this in python:我想在 python 中将它们存储为这样的键值对:

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

Here is my code:这是我的代码:

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

output looks like this:输出如下所示:

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

But I would like the "", <> removed and id to be stored as type int但我希望将 "", <> 删除并将 id 存储为 int 类型

Don't do line[1:] to strip away the brackets.不要用line[1:]去掉括号。 Use the strip method: line.strip(' <>') will remove all whitespace and <> characters from the ends of the line.使用strip方法: line.strip(' <>')将从行尾删除所有空格和 <> 字符。

Something like this will do what I think you want.像这样的事情会做我认为你想要的。 You may want to add error handling.您可能想要添加错误处理。

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

暂无
暂无

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

相关问题 如何在Python的字典中存储文件? - How do I store a file in a dictionary in Python? 如何创建自定义标签以在命令行中获取输入字符串并将它们存储在 Python 的变量中 - How do i create custom tags for taking the input string in command line and store them in a variable in Python 如何在一行中将输入写入文件并将多个输入存储到文件中并能够读取它们? - How do I write input to files in one line and store multiple inputs to the file and be able to read them? 如何从文本文件中获取每一行并将其拆分,以便我可以在 python 中单独使用它们 - How do I get each line from a text file and split it so that I can use them all separately in python 如何允许Python从2个文本文件(同一行)中选择一条随机行,然后将其存储为变量? - How do I allow Python to choose a random line from 2 text files (that are the same line) and then store them as variables? 如何将 object 存储在 Python 的字典中? - How do I store an object in a dictionary in Python? Python,json,附加到一行字典{}{}{}{}{},如何一一阅读? - Python, json, appending to one line dictionary {}{}{}{}{}, how do i read them one by one? Python:如何拆分文件中的每一行代码并添加到字典中 - Python: How to Split Each Line of Code in a File and Add to a Dictionary 如何让 Python 在第一行开始读取文件? - How do I get Python to starting reading a file on the first line? 如何将 python 字典的每个键值对存储在 json 文件中的单独行上? - How can I store each key-value pair of my python dictionary on a separate line in json file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM