如何在python中合并已读文档中的每3行

2024-04-28 04:32:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在阅读一份输出如下的文件:

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)  

此代码只会根据需要返回文档的前三行。我在这个网站上尝试过其他解决方案,但它们都将整个文档合并成一个长字符串。你知道吗


Tags: ifcountlineproductpricequantitythinoriginal
2条回答

这种任务在^{} recipe documentationgrouper中有一个完美的匹配

from itertools import zip_longest
# in case you use python 2 use "from itertools import izip_longest as zip_longest

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x')  > ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

然后你可以使用:

with open('test.txt','r') as document:
    res = [', '.join(group) for group in grouper(map(str.strip, document), 3)]

为了说明它的大致工作原理,我将字符串作为行列表包括在内:

astring = """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""".split('\n')

[','.join(group) for group in grouper(astring, 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']

你可以试试这个:

data = [i.strip('\n') for i in open('filename.txt')]

new_data = [' ,'.join(data[i:i+3]) for i in range(0, len(data), 3)]

f = open('filename.txt', 'w')
for i in new_data:
   f.write("{}\n".format(i))

f.close()

相关问题 更多 >