如何根据元素的子字符串将元素从文本文件中分离为2个输出文件



我在一个文本文件中有一长串动物标识符。我们的惯例是使用两个字母字符,然后是垃圾标识符一个破折号,然后是该垃圾中的动物id。短划线前的数字表示它们是受控动物还是被操纵动物。

所以它看起来是这样的:(括号中的解释不在文本文件中(文本文件中唯一的东西是标识符,可能还有同一行上该标识符之后的数据。

XL20-4是对照动物(0-偶数(,

XL21-4是一种被操纵的动物(1-奇数(,

一直运行到300年代的

XL304-5 (4 - even - control), 
XL303-4 (3 - odd - manipulated).

首先,如何在原始文本文件的每个条件下,在动物的单独文本文件中创建一个有序列表,这样我们的matlab代码就可以读取它。

它需要在这些新的文本文件中保留动物生成的顺序即

XL302-4, 
XL304-5, 
XL304-6, 
XL306-1, 

每个都有一个'/n'结尾。

提前谢谢。

根据您所说的,这将是实现它的方法,但应该有一些更精细的调整,因为文件内容最初是未知的(名称和它们在文本文件中的放置方式(

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.find('-')])
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)

最新更新