我正在尝试将文本文件读取到Python中的嵌套列表中。也就是说,我希望将输出显示为:
[[$5.79, Breyers Ice Cream, Homemade Vanilla, 48 oz], [$6.39, Haagen-dazs, Vanilla Bean Ice Cream, 1 pt], etc...]]
最终目标是将信息读入pandas DataFrame中进行一些探索性分析。
$5.79
Breyers Ice Cream
Homemade Vanilla
48 oz
$6.39
Haagen-dazs
Vanilla Bean Ice Cream
1 pt
$6.89
So Delicious
Dairy Free Coconutmilk No Sugar Added Dipped Vanilla Bars
4 x 2.3 oz
$5.79
Popsicle Fruit Pops Mango
12 ct
with open(sample.txt) as f:
creams = f.read()
creams = f.split("\n\n")
但是,这返回:
['$5.79\nBreyers Ice Cream\nHomemade Vanilla\n48 oz', '$6.39\nHaagen-dazs\nVanilla Bean Ice Cream\n1 pt',
我还尝试使用看起来比上面的代码更干净的列表理解方法,但是这些尝试处理换行符,而不是段落或返回值。例如:
[x for x in open('<file_name>.txt').read().splitlines()]
#Gives
['$5.79', 'Breyers Ice Cream', 'Homemade Vanilla', '48 oz', '', '$6.39', 'Haagen-dazs', 'Vanilla Bean Ice Cream', '1 pt', '', '
我知道我需要在列表理解中嵌套一个列表,但是我不确定如何执行拆分。
注意:这是我第一个发布的问题,对您的简短或简短表示抱歉。寻求帮助,因为存在类似的问题,但我希望得到的结果却没有。
一旦分隔四行组,您就快到了。剩下的就是用单个换行符再次将组拆分。
with open('creams.txt','r') as f:
creams = f.read()
creams = creams.split("\n\n")
creams = [lines.split('\n') for lines in creams]
print(creams)
您只需要再次拆分即可。
with open('sample.txt','r') as file:
creams = file.read()
creams = creams.split("\n\n")
creams = [lines.split('\n') for lines in creams]
print(creams)
#[['$5.79 ', 'Breyers Ice Cream ', 'Homemade Vanilla ', '48 oz'], ['$6.39 ', 'Haagen-dazs ', 'Vanilla Bean Ice Cream ', '1 pt'], ['$6.89 ', 'So Delicious ', 'Dairy Free Coconutmilk No Sugar Added Dipped Vanilla Bars ', '4 x 2.3 oz'], ['$5.79 ', 'Popsicle Fruit Pops Mango', '-', '12 ct']]
#Convert to Data
df = pd.DataFrame(creams, columns =['Amnt', 'Brand', 'Flavor', 'Qty'])
Amnt Brand \
0 $5.79 Breyers Ice Cream
1 $6.39 Haagen-dazs
2 $6.89 So Delicious
3 $5.79 Popsicle Fruit Pops Mango
Flavor Qty
0 Homemade Vanilla 48 oz
1 Vanilla Bean Ice Cream 1 pt
2 Dairy Free Coconutmilk No Sugar Added Dipped V... 4 x 2.3 oz
3 - 12 ct
注:由于在风味列中没有添加,因此我在最后一行中添加了-
。如果是原始数据集,则在执行任何分析之前必须考虑到这一点。