Home > database >  Rearrange txt content Script
Rearrange txt content Script

Time:02-06

I have a list of predators and their corresponding preys in this format:

Wolf: Sheep, Chicken, Rabbit
Lion: Zebra, Giraffe, Gazelle

And want to transform it to this format:

Wolf Sheep
Wolf Chicken
Wolf Rabbit
Lion Zebra
Lion Giraffe
Lion Gazelle

So far, I have tried this code in order to separate predators and preys

with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    split = (line.split(":") for line in stripped if line)
    pred = []
    for line in split:
        pred.append(line[0])

with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    split = (line.split(":") for line in stripped if line)
    preys = []
    for line in split:
        preys.append(line[1])
    prey = (line.split(",") for line in preys if line)

But combining them is the problem. I have tried something close to this:

with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    i=0
    while i < line_count:
        rows.append(pred[i])
        for line in prey:
            rows.append(line[0])
        i =1

CodePudding user response:

you can read in the items like this:

with open('test.txt','r') as in_file:
    dict_predators = {}
    for line in in_file:
        dict_predators[line.split(':')[0]] = line.split(':')[1].replace('\n', '').split(',')

first split the line by the ':' use both of those elements one the first part as the key in a dictionary and the second part as a list for the value in the dictionary (I used replace to get rid of the newline character) and then used split by ',' to make them into strings (with a space before because you were already going to use a space when you print them back out)

And you can write them to a file like this:

with open('test2.txt','w') as in_file:
    for k,v in dict_predators.items():  # go through all the elements in the dictionary
        for item in v:  # go through all the elements of the list of values at that key
            in_file.write(f"{k}{item}\n")

CodePudding user response:

If you can use itertools and re module, I would go with something like:

import itertools, re
with open('test.txt','r') as inFile:
    with open('test2.txt','w') as outFile:
        for line in inFile:
            splitted = re.split(":|,", line.strip())
            predator = splitted[0]
            preys = splitted[1:]
            content = zip(itertools.repeat(predator), preys)
            outFile.write('\n'.join([ ''.join(item) for item in content ]))

How it works:

  1. reads input file line by line;
  2. for each line, it first strip the line and then split it using both colon and comma as separators;
  3. puts the predator and the preys in two named variables to make code clear;
  4. prepares the content using zip and itertools.repeat;
  5. creates a list of "joined" item for item in content, using an empty string as joiner;
  6. creates a string joining the previous list elements with '\n' as joiner;
  7. writes it to outFile.

note: It's possible to write a single with/as statement:

with open('test.txt','r') as inFile, open('test2.txt','w') as outFile:
  •  Tags:  
  • Related