简体   繁体   English

读取文本文件以创建列表,然后转换为字典 python

[英]Read text file to create list and then convert to dictionary python

I am reading text file using我正在使用

source= open(curr_file,"r")
lines= source.readlines()

This converts every line in my text file to a list, but some items in my list are created with double quotes while some are created with single quotes like below.这会将我的文本文件中的每一行都转换为一个列表,但我的列表中的某些项目是用双引号创建的,而有些则是用单引号创建的,如下所示。

['[INFO] Name: Xxxx, section: yyyy, time: 21.2, status: 0\n', "proof:proof1,table: db.table_name,columns:['column_1'],count:10,status:SUCCESS\n",'run time: 30 seconds\n']

The first item in list is created with single quotes, while the second is created with double quotes.列表中的第一项是用单引号创建的,而第二项是用双引号创建的。

When trying to convert the above to dictionary尝试将上述内容转换为字典时

new_line= dict(x.split(":"),1) for x in line.split(","))

It gives me a value error它给了我一个值错误

Value error: dictionary update sequence element has length 1; 2 is required

The above error is because it considers the entire string under double quotes as single value and it's not able to convert it to dictionary.上述错误是因为它将双引号下的整个字符串视为单个值,并且无法将其转换为字典。

Is there a way to convert it to single quotes instead of double.有没有办法将其转换为单引号而不是双引号。 I tried using replace, strip.我尝试使用替换,剥离。 But nothing helps.但没有任何帮助。

Expected output: { Name:Xxxx, section:yyyy, time:21.2, proof:proof1 table:db.table_name status: success }预期输出:{ Name:Xxxx, section:yyyy, time:21.2, proof:proof1 table:db.table_name status: success }

The quotes has nothing to do with the error.引号与错误无关。 The exterior quotes of each line are not part of the str object.每行的外部引号不是 str 对象的一部分。 They are only printed to you know it is a str.他们只打印给你知道它是一个str。 The single quotes are switched to double because the content has single quotes in it, then single quotes cannot be used to delimit the str.单引号因为内容里面有单引号所以切换成双引号,那么就不能用单引号来分隔str了。 But again, that is only a change in what is printed not in what is stored in memory.但同样,这只是打印内容的变化,而不是存储在内存中的内容。

Try to do it in steps and print the intermediate objects you get to debug the program.尝试分步执行并打印调试程序所需的中间对象。

for x in line: #prints nicer than print(line)
    print(x)

arg = [x.split(":",1) for x in line.split(",")]

for x in arg:    
    print(x)

new_line = dict(arg)

you should get printed tuples with two elements你应该得到带有两个元素的打印元组

要将一行(str)转换为dict,您可以使用字典理解:

new_line = dict(x.split(":",1) for x in line.split()

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

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