Guilherme Tell Benevenuto Apolinario commited on
Commit
c0220f0
·
verified ·
1 Parent(s): ed9658a

Upload data_cleaning.py

Browse files
Files changed (1) hide show
  1. data_cleaning.py +124 -0
data_cleaning.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import chardet
2
+ import pandas as pd
3
+ import regex
4
+
5
+
6
+ def iniciar(file_path):
7
+ """
8
+ A function that detects the encoding of a file and reads the file using the detected encoding.
9
+
10
+ Parameters:
11
+ - file_path (str): The path to the file to be read.
12
+
13
+ Returns:
14
+ - str: The data read from the file.
15
+ """
16
+ # Detectar a codificação do arquivo
17
+ with open(file_path, "rb") as file:
18
+ raw_data = file.read()
19
+ result = chardet.detect(raw_data)
20
+ encoding = result["encoding"]
21
+ print(f"Detected encoding: {encoding}")
22
+
23
+ # Ler o arquivo com a codificação detectada
24
+ with open(file_path, "r", encoding=encoding) as file:
25
+ csv_data = file.read()
26
+
27
+ return csv_data
28
+
29
+
30
+ def limpa_rci(texto):
31
+ """
32
+ Cleans up the given text by removing unwanted parts.
33
+
34
+ Args:
35
+ texto (str): The text to be cleaned.
36
+
37
+ Returns:
38
+ str: The cleaned text.
39
+ """
40
+ # Remover partes indesejadas
41
+ sub1 = r"(^e-SUS.+\nMIN(.+\n+){7}.+)|((?<=Equipe;)\d+\s\-\s)|(^CBO.+\n(.+\n+){8}.+)|(^Não\sinf.+\n+Identif.+\nDes.+\nDes.+\nDes.+\nRes.+\n+Iden.+$)|(^Não\sin.+\n+Ident.+Cor$)|(^Não\sin.+\n+Ident.+\nDesc.+\nBra.+\nNat(.+\n+){34}.+)|(^Inf.+\nDesc.+\nAdult.+\n(.+\n+){10}.+)|(^Inf.+\n(Des.+\n){3}.+$)|(^Inf.+\nDesc.+\n(Tem\salg.+\n){1}.+$)|(^Inf.+\nA\slist.+\nDes(.+\n+){8}.+$)|(^Cidadão.+\nDesc.+\nÉ.+\nPossu(.+\n*)*)|(^Não\sinf.+;0.+$)|(;;;;;|;;;;|Ident.+(-|/)\s)|((?<=Saída)\sde.+tro|.+(?=ativos))|"
42
+ sub2 = r"(^C.*(rin|card|resp).+\n.+\n.+[os]\s)|(;;;\nT.+\nT.+$)|(;Sim|(?<=[az];);|\ssabe;|\s.\sEnfisema)|(^Participa.+$|Poss.+de\s|(?<=privado.;\d\d\d);.+|Poss.+de\s|(?<=privado.;\d\d\d\d);.+)|((Desc.+\n){3}Resp.+$)|(Etnia.+\nD.+\nNã.+$)|(Nacio.+\nDesc.+\nB.+\nNat.+\nEst.+$)|(Infor.+\nDesc.+\nCôn(.+\n){31}Inf.+$)|Deseja\sinf.+$|(?<=Ensino\s[fm][ué][nd]).+(\)|[eat][lso])|(?<=Pré).+\)|(Classe\sde\salfa.+-\s)|((?<=Superior).+rado)|((?<=Alfabet).+\))|(Infor.+\nDesc.+\nEmpreg(.+\n){10}.+$)|Intelec.+/\s|((Está\s(com\s)?))|(^Condiç.+\nD.+$)|((Faz\suso.+e\s)|PIC;.+|Tem\s|ou\steve\s|Teve\s|internação.+\nUsa\splant.+$|\s/\sderrame|diagnóst.+de\s)"
43
+ rx_marc = sub1 + "|" + sub2
44
+ # Remover partes indesejadas
45
+ texto = regex.sub(rx_marc, "", texto, flags=regex.MULTILINE)
46
+
47
+ tira = r"(;;;)"
48
+ texto = regex.sub(tira, "", texto, flags=regex.MULTILINE)
49
+ tira = r"(;;)"
50
+ texto = regex.sub(tira, ";", texto, flags=regex.MULTILINE)
51
+ return texto
52
+
53
+
54
+ def separa_grupos(texto):
55
+ """
56
+ A function that uses a regular expression to extract various groups from the input text.
57
+
58
+ Args:
59
+ texto (str): The input text from which groups are extracted.
60
+
61
+ Returns:
62
+ dict: A dictionary containing different groups extracted from the text like 'Idade', 'genero', 'cor', 'deficiencia', and 'doencas'.
63
+ """
64
+ # Expressão regular ajustada para capturar vários grupos
65
+ grupos = r"""
66
+ ((?P<Data>Data);\d+/\d+/\d+)|
67
+ ((?P<Head>[EPCS][aqri][uodí].+;)\w+)|
68
+ (?P<Idade>(^Menos.+(?=;0)|^[0-9][0-9]\s\w).+(?=;0))|
69
+ (?P<genero>(^(Masc.+|Fem.+)))|
70
+ (?P<cor>(^(Bra.+$|Pret.+$|Amar.+$|Par.+$|Indí.+$)))|
71
+ (?P<deficiencia>(^(Audi.+a;\d+|Fís.+a;\d+|Cogn.+a;\d+|Vis.+l;\d+\nOut.+$)))|
72
+ (?P<doencas>(^(hipert.+al;\d+|diab.+s;\d+|gesta.+e;\d+|acam.+o;\d+|domici.+o;\d+)))
73
+ """
74
+
75
+ # Compilar a expressão regular com as flags re.VERBOSE e re.MULTILINE para maior legibilidade
76
+ pattern = regex.compile(grupos, regex.VERBOSE | regex.MULTILINE)
77
+
78
+ matches = pattern.finditer(texto)
79
+ grupos_enc = {
80
+ "Idade": [],
81
+ "genero": [],
82
+ "cor": [],
83
+ "deficiencia": [],
84
+ "doencas": [],
85
+ }
86
+
87
+ for match in matches:
88
+ for group_name, group_value in match.groupdict().items():
89
+ if group_value and group_name in grupos_enc:
90
+ grupos_enc[group_name].append(group_value)
91
+
92
+ return grupos_enc
93
+
94
+
95
+ def criar_dataframe(grupos_encontrados):
96
+ """
97
+ Create dataframes based on the groups found in `grupos_encontrados`.
98
+
99
+ Args:
100
+ grupos_encontrados (dict): A dictionary containing the groups found and their corresponding values.
101
+
102
+ Returns:
103
+ dict: A dictionary containing the created dataframes, where the keys are the group names and the values are the corresponding dataframes.
104
+ """
105
+ dataframes = {}
106
+ for grupo, valores in grupos_encontrados.items():
107
+ if grupo == "Idade":
108
+ df = pd.DataFrame(valores, columns=["Descrição"])
109
+ df["Masculino"] = df["Descrição"].apply(lambda x: x.split(";")[1])
110
+ df["Feminino"] = df["Descrição"].apply(lambda x: x.split(";")[2])
111
+ df["Descrição"] = df["Descrição"].apply(lambda x: x.split(";")[0])
112
+ else:
113
+ # Tratar casos onde os dados são separados por '\n'
114
+ novos_valores = []
115
+ for valor in valores:
116
+ partes = valor.split("\n")
117
+ novos_valores.extend(partes)
118
+ df = pd.DataFrame(novos_valores, columns=["Descrição"])
119
+ df["Valor"] = df["Descrição"].apply(lambda x: x.split(";")[-1])
120
+ df["Descrição"] = df["Descrição"].apply(
121
+ lambda x: ";".join(x.split(";")[:-1])
122
+ )
123
+ dataframes[grupo] = df
124
+ return dataframes