Hello! There is a .txt file, the lines in which are arranged as follows (text is different everywhere, a and b are the same for each line):

a "text" b "text" a "text" b "text" ... 

It is necessary to turn the text into pairs:

 a "text" - b "text" a "text" - b "text" 

I will be glad to any advice: how to do it, in what direction to dig, etc.

    1 answer 1

    Well, I would have done it like this if I understood the question correctly and if I need to save to the file:

     in_file = "IN.txt" out_file = "OUT.txt" data_file = [] # ΠžΡ‚ΠΊΡ€Ρ‹Π»ΠΈ, ΠΏΡ€ΠΎΡ‡ΠΈΡ‚Π°Π»ΠΈ, ΠΏΠΎΠ»ΡƒΡ‡ΠΈΠ»ΠΈ список with open(in_file, 'r') as read_file: for line in read_file: data_file.append(line.strip('\n')) # Π‘ΠΎΠ΅Π΄ΠΈΠ½ΠΈΠ»ΠΈ ΠΈΠ· списка Π² строку, записали построчно with open(out_file, 'a') as save_file: tmp_string = '' for num, line in enumerate(data_file): if num % 2 == 0: tmp_string = line continue else: result = '%s - %s\n' % (tmp_string, line) save_file.write(result) 

    But this is if the lines go one by one in order and never change. Those. is always:

     a "text" b "text" 

    The result will be:

     a "text" - b "text" a "text" - b "text" 

    If there is also a c "text":

     in_file = "IN.txt" out_file = "OUT.txt" data_file = [] # ΠžΡ‚ΠΊΡ€Ρ‹Π²Π°Π΅ΠΌ ΠΈ парсим Ρ„Π°ΠΉΠ» with open(in_file, 'r') as read_file: tmp_string = '' # ΠŸΠ΅Ρ€Π΅Π±ΠΈΡ€Π°Π΅ΠΌ Ρ„Π°ΠΉΠ» ΠΏΠΎ строкам ΠΈ сравниваСм Π½Π°Ρ‡Π°Π»ΡŒΠ½Ρ‹ΠΉ символы строки for line in read_file: my_string = line.strip('\n') if my_string[0] == "c": data_file.append(my_string) if my_string[0] == "a": tmp_string = my_string if my_string[0] == "b": tmp_string = '%s - %s' % (tmp_string, my_string) data_file.append(tmp_string) tmp_string = '' # БохраняСм Π² Π½ΠΎΠ²ΠΎΠΌ Ρ„Π°ΠΉΠ»Π΅ with open(out_file, 'a') as save_file: for line in data_file: save_file.write('%s\n' % line) 

    Of

     c "text" a "text" b "text" a "text" b "text" c "text" 

    We get:

     c "text" a "text" - b "text" a "text" - b "text" c "text" 
    • Thanks for the answer! And if sometimes there will be a third line to be left as is, that is: c "text2" a "text" b ​​"text" Turn into: c "text2" a "text" - b "text"? - kamaz914
    • Give an example file please. How about there in fact. Or will it be with you: with "text2" a "text" b ​​"text"? - WorldCount