我正在阅读一份输出如下的文件:
Pretzel Crisps Original/Thin/Crunchy Pretzel Crackers Pretzels, 7.2 oz
1 × $2.14
$2.14
Bagel Bites Cheese & Pepperoni Mini Bagels, 40 count, 31.1 oz
1 × $7.98
$7.98
SuperPretzel Cheddar Cheese Filled Soft Pretzel Sticks Softstix, 9 Oz
1 × $2.56
$2.56
我想将每3行合并为一行,如下所示:
Pretzel Crisps Original/Thin/Crunchy Pretzel Crackers Pretzels 7.2 oz, 1 × $2.14, $2.14
Bagel Bites Cheese & Pepperoni Mini Bagels 40 count 31.1 oz, 1 × $7.98, $7.98
SuperPretzel Cheddar Cheese Filled Soft Pretzel Sticks Softstix 9 Oz, 1 × $2.56, $2.56
我尝试了以下代码:
product=[]
quantity=[]
price=[]
count=1
with open('test.txt','r')as document:
for line in document:
line=line.replace('\n','')
if count == 1:
line=line.replace(',','')
product.append(line)
if count == 2:
quantity.append(line)
if count == 3:
price.append(line)
count+=1
all=list(zip(product,quantity,price))
print(all)
此代码只会根据需要返回文档的前三行。我在这个网站上尝试过其他解决方案,但它们都将整个文档合并成一个长字符串。你知道吗
这种任务在^{} recipe documentation :
grouper
中有一个完美的匹配然后你可以使用:
为了说明它的大致工作原理,我将字符串作为行列表包括在内:
你可以试试这个:
相关问题 更多 >
编程相关推荐