[英]Python read text file with newline and and paragraph separated elements
我正在嘗試將文本文件讀取到 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
注意:我在風味列的最后一行添加了-
因為它是空的。 如果是原始數據集,則必須在執行任何分析之前考慮到這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.