Python 并读取包含字符串和数字列表的文本文件 [英] Python and read text file that contains lists with strings and numbers
问题描述
这是一个与许多人类似但又不完全相同的问题.我有一个包含大约 400,000 行文本的文本文件.每一行本质上都是一个列表.例如它看起来像 [ 'a','b',1,2,'c',3,'d and , e string', 45]
This is a similar question to many but not quite the same. I have a text file that has about 400,000 lines of text. Each line is essentially a list. For example it looks like [ 'a','b',1,2,'c',3,'d and , e string', 45]
我可以使用以下代码读取文本文件的每一行:
I can read each line of the text file with the following code:
with open('myfile.txt') as f:
content = f.readlines()
问题是每一行都被读为一个字符串.我想获取列表中的每个项目.所以我想我会做(对于每一行):
The problem is that each line is read as a string. I would like to get each item of the list. So i thought i would do (for each line):
content[line].split(',')
这几乎有效,但我遇到了问题.很多时候在我的文本文件中,我在列表中有一个字符串,其中包含一个逗号(从上面我有 'd 和 , e 字符串').我不希望这个字符串分开,但希望它作为一个项目.
This almost works, but i run into a problem. Many times in my text file i have a string in the list that has a comma in it (from above i had 'd and , e string'). I don't want this string split up but want it as one item.
如果这不行,因为我想从我的文本文件中取出一行 [ 'a','b',1,2,'c',3,'d and , e string',45]
我想要 8 个单独的元素
If this doesn't make since I want to take the line from my text file [ 'a','b',1,2,'c',3,'d and , e string', 45]
and i want 8 separate elements
'a'
'b'
1
2
'c'
3
'd and , e string'
45
感谢您的帮助!
推荐答案
DSM 对
from ast import literal_eval
# use generator
# instead of allocating
# 400 000 lists at a time
your_lists = (literal_eval(s) for s in open('filename.txt'))
这篇关于Python 并读取包含字符串和数字列表的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!