Python-格式化文件以列出 [英] Python - Format file to list
本文介绍了Python-格式化文件以列出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经阅读了一些有关如何将文件传递到列表的问题,但是此文件有点棘手,因为其中包含不同的数据类型,所有这些数据类型都在该文件中表示为字符串.
I've read some questions on how to pass a file to a list, but this file it's a bit trickier as there are different data types in it, all of them represented as a string in that file.
我设法获得了一个看起来像这样的文件:
I've managed to get a file that looks like this:
['verb', 0, 5, 7]['noun', 9, 3, 4]
如何将其转换为类似于以下内容的列表:
How can I turn this into a list that looks like:
list = [['verb', 0, 5, 7], ['noun', 9, 3, 4]]
其中'verb'
和'noun'
是字符串,所有数字都是整数.
where 'verb'
and 'noun'
are strings and all numbers are integers.
推荐答案
您可以尝试以下操作:
data = open('file.txt').read().strip('\n')
import re
lists = re.findall("\[(.*?)\]", data)
final_list = [[int(i) if i.isdigit() else i[1:-1] for i in b.split(", ")] for b in lists]
这篇关于Python-格式化文件以列出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文