[英]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
所以我有一些很長的動物標識符列表。 我們的約定是使用兩個字母字符,后跟一個垃圾標識符,一個破折號,然后是該垃圾中的動物 ID。 破折號前的數字標識它們是受控動物還是受操縱動物。
所以它看起來像這樣:
XL20-4 是對照動物(0 - 偶數),XL21-4 是操縱動物(1 - 奇數),
這一直持續到 300 秒。
所以我們目前的窩是:XL304-5(4 - 偶數 - 控制),XL303-4(3 - 奇數 - 操縱)。
所以我的首要任務之一是從原始文本文件中創建每種條件下動物的有序文本文件,以便我們的 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.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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.