python:获得多对基因集的差集、交集
2021-03-25 本文已影响0人
胡童远
计算两对基因集的差:
cat list.txt
X-4 X-31
W-4 W-6
输入数据:
├── list.txt
├── Prokka
│ ├── W-4
│ │ ├── W-4.gene
│ ├── W-6
│ │ ├── W-6.gene
│ ├── X-31
│ │ ├── X-31.gene
│ └── X-4
│ ├── X-4.gene
核心方法:
1 for循环遍历基因集对,获取输入文件路径
2 readlines读取,set进行集合操作
3 readlines保留了换行符,因此格式化输出不用加换行
#!/usr/bin/env python3
import sys, os, re
# 路径
Prokka="Prokka"
if os.path.exists("Result"):
print("\033[32m Directory Result Existed! \033[0m")
else:
os.makedirs("Result")
# 计数
num = 1
# 存储篮
one_uniq = []
intersec = []
two_uniq = []
# 遍历目标
with open("list.txt", 'r') as f:
for line in f:
line = line.strip()
g_1 = re.split(r'\t', line)[0]
g_2 = re.split(r'\t', line)[1]
f_1="{}/{}/{}.gene".format(Prokka, g_1, g_1)
f_2="{}/{}/{}.gene".format(Prokka, g_2, g_2)
# 打开目标文件
with open(f_1, 'r') as f_1:
f_1 = f_1.readlines()
with open(f_2, 'r') as f_2:
f_2 = f_2.readlines()
# 差集,交集,补集
one_uniq = set(f_1) - set(f_2)
intersec = set(f_1) & set(f_2)
two_uniq = set(f_2) - set(f_1)
# 输出
o_1 = "Result/{}_{}_one_uniq.txt".format(g_1, g_2)
o_2 = "Result/{}_{}_intersec.txt".format(g_1, g_2)
o_3 = "Result/{}_{}_two_uniq.txt".format(g_1, g_2)
with open(o_1, 'w') as out_1:
with open(o_2, 'w') as out_2:
with open(o_3, 'w') as out_3:
out_1.write(''.join(one_uniq))
out_2.write(''.join(intersec))
out_3.write(''.join(two_uniq))
# 屏幕打印提示
print("\033[32m {} {} {} DONE!\033[0m".format(num, g_1, g_2))
num = num + 1
结果:
└── Result
├── W-4_W-6_intersec.txt
├── W-4_W-6_one_uniq.txt
├── W-4_W-6_two_uniq.txt
├── X-4_X-31_intersec.txt
├── X-4_X-31_one_uniq.txt
└── X-4_X-31_two_uniq.txt