#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author :yzj
# @FileName :baoliu.py
# @Time :2023/5/9 11:23
import re
import glob
import os


class GeneAnalysis_diushi:
    def __init__(self, input_file, output_file):
        self.input_file = input_file
        self.output_file = output_file
        self.array = []
        self.n = 0
        self.all = []
        self.hash = {}

    def read_input(self):
        with open(self.input_file, 'r') as f:
            for line in f:
                line = line.strip()
                if 'scaffold' in line:
                    continue
                if re.search(r'\d+s\d+', line):
                    continue
                arr = line.split("\t")
                self.n = len(arr) - 1
                chr_num = re.search(r'\d+', arr[0]).group()
                arr[0] = chr_num
                self.array.append(arr)

    def process_data(self):
        """
        处理数据，统计每个数字出现的次数
        """
        for i in range(1, self.n):
            a = 0
            chr_num = ''
            for j in range(len(self.array)):
                if j == 0:
                    chr_num = self.array[j][0]
                if self.array[j][i] == ' ':
                    continue
                if not re.search(r'\d+', self.array[j][i]) and self.array[j][0] == chr_num:
                    a += 1
                else:
                    self.all.extend([a, 0])
                    chr_num = self.array[j][0]
                    a = 0
                    self.all.extend([a])
                if j == len(self.array) - 1:
                    self.all.append(a)

        for item in self.all:
            if item in self.hash:
                self.hash[item] += 1
            else:
                self.hash[item] = 1

        with open(f"output/{self.output_file}", 'w') as f:
            for key in sorted(self.hash.keys()):
                f.write(f"{key}\t{self.hash[key]}\n")




if __name__ == '__main__':
    input_files = glob.glob("orthomcl/*")
    for line in input_files:
        file_name = os.path.basename(line).split(".")[0]
        output_file_path = f"{file_name}_lost.txt"

        gene_analysis = GeneAnalysis_diushi(line, output_file_path)  # 改 输入mc文件和生成结果文件
        gene_analysis.read_input()
        gene_analysis.process_data()


