gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:40:15 25 4
gpt4 key购买 nike

我正在阅读文档,输出如下:

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)

此代码将仅根据需要返回文档的前三行。我在该站点上尝试过其他解决方案,但它们都将整个文档组合成一个长字符串。

最佳答案

itertools recipe documentation 中有此类任务的完美匹配: 石斑鱼

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']

关于python - 如何在 python 中合并读取文档中的每 3 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45787815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com