2017-08-20 3 views
2

Je lis un document avec la sortie comme suit:Comment combiner tous les 3 lignes d'un document de lecture en 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 

je voudrais combiner toutes les 3 lignes sur une nouvelle ligne comme suit:

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 

J'ai essayé le code suivant:

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) 

Ce code renverrons seulement les trois premières lignes du document comme voulu. J'ai essayé d'autres solutions sur ce site, mais tous combinent le document entier en une longue chaîne.

+0

semble tout à fait semblable à https://stackoverflow.com/questions/45774259/python-how-to-extract-specific-string-into-multiple-variable/45775212#45775212 –

Répondre

1

Vous pouvez essayer ceci:

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() 
2

Il y a un match parfait pour ce genre de tâche dans le itertools recipe documentation: grouper

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) 

Ensuite, vous pouvez utiliser:

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

Juste pour illustrer comment cela fonctionne à peu près, j'ai inclus la chaîne comme liste de lignes:

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