简体   繁体   中英

Python - How to sort textfile by odd and even number at third element or fourth element and produce output textfiles of odd or even numbered entries

So I have some big long lists of animal identifiers. Our convention is to use two of alphabetical characters, followed by a litter identifier a dash and then the animal id within that litter. The number before the dash identifies whether they are control or manipulated animals.

So it looks like this:

XL20-4 is a control animal (0 - even), XL21-4 is a manipulated animal (1 - odd),

this runs all the way through to 300s.

So our current litters are: XL304-5 (4 - even - control), XL303-4 (3 - odd - manipulated).

So one of my first tasks is to create ordered textfiles of the animals in each condition from the original text file, so it can then be read by our matlab code.

Essentially, it needs to retain the order of animal generation within those new textfiles ie XL302-4, XL304-5, XL304-6, XL306-1,

Each with a /n. I know this isn't so easy, but I've done quite a bit of looking and I think this is a bit beyond me.

Thanks in advance.

based on what you had said this would be the way to do it, but there should be some finer tweaking because the file contents originally are unknown (name and how they are placed in the text file)

import re

def write_to_file(file_name, data_to_write):
    with open(file_name, 'w') as file:
        for item in data_to_write:
            file.write(f"{item}\n")

# read contents from file
with open('original.txt', 'r') as file:
    contents = file.readlines()

# assuming that each of the 'XL20-4,' are on a new line
control_group = []
manipulated_group = []
for item in contents:
    # get only the first number between the letters and dash
    test_generation = int(item[re.search(r"\d", item).start():item.rfind('-')])
    if test_generation % 2: # if even evaluates to 0 ~ being false
        manipulated_group.append(item)
    else:
        control_group.append(item)

# write to files with the data
write_to_file('control.txt', control_group)
write_to_file('manipulated.txt', manipulated_group)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM