Python 读取带有换行符和段落分隔元素的文本文件



我正在尝试将文本文件读取到Python中的嵌套列表。也就是说,我希望输出为:

[[$5.79, Breyers Ice Cream, Homemade Vanilla, 48 oz], [$6.39, Haagen-dazs, Vanilla Bean Ice Cream, 1 pt], etc...]]

最终目标是将信息读入熊猫数据帧以进行一些探索性分析。

数据(在.txt文件中(

$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("nn")

但是,这将返回:

['$5.79nBreyers Ice CreamnHomemade Vanillan48 oz', '$6.39nHaagen-dazsnVanilla Bean Ice Creamn1 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("nn")
creams = [lines.split('n') for lines in creams]
print(creams)

你只需要再次拆分它。

with open('sample.txt','r') as file:
creams = file.read()
creams = creams.split("nn")
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  

注意:我在风味列的最后一行添加了-,因为它是空的。如果是原始数据集,则在执行任何分析之前必须考虑到这一点。

最新更新