inclusao de gabarito

This commit is contained in:
Felipe Domingos da Cunha 2022-03-15 16:43:52 -03:00
parent cdc9b6b038
commit dd985a7983
2 changed files with 0 additions and 418 deletions

View File

@ -1,238 +0,0 @@
/**
* Classe Série
* TP - Algoritmos e Estruturas de Dados II
* @author - João Augusto dos Santos Silva
* 2021 - 2o. Semestre
*/
import java.io.*;
import java.io.FileReader;
class Serie {
//declaração dos atributos
private String name;
private String format;
private String duration;
private String country;
private String language;
private String broadcaster;
private String streaming;
private int seasons;
private int episodes;
//construtor primário
public Serie(){
name = "";
format = "";
duration = "";
country = "";
language = "";
broadcaster = "";
streaming = "";
seasons = 0;
episodes = 0;
}
//construtor secundário
public Serie(String name, String format, String duration, String country, String language, String broadcaster, String streaming, int seasons,
int episodes){
this.name = name;
this.format = format;
this.duration = duration;
this.country = country;
this.language = language;
this.broadcaster = broadcaster;
this.streaming = streaming;
this.seasons = seasons;
this.episodes = episodes;
}
//método para setar o atributo name
public void setName(String name){
this.name = name;
}
//método para setar o atributo formato
public void setFormat(String format){
this.format = format;
}
//método para setar o atributo duration
public void setDuration(String duration){
this.duration = duration;
}
//método para setar o atributo country
public void setCountry(String country){
this.country = country;
}
//método para setar o atributo language
public void setLanguage(String language){
this.language = language;
}
//método para setar o atributo broadcaster
public void setBroadcaster(String broadcaster){
this.broadcaster = broadcaster;
}
//método para setar o atributo streaming
public void setStreaming(String streaming){
this.streaming = streaming;
}
//método para setar o atributo seasons
public void setSeasons(int seasons){
this.seasons = seasons;
}
//método para setar o atributo episodes
public void setEpisodes(int episodes){
this.episodes = episodes;
}
//método para retornar o atributo name
public String getName(){
return this.name;
}
//método para retornar o atributo format
public String getFormat(){
return this.format;
}
//método para retornar o atributo duration
public String getDuration(){
return this.duration;
}
//método para retornar o atributo country
public String getCountry(){
return this.country;
}
//método para retornar o atributo language
public String getLanguage(){
return this.language;
}
//método para retornar o atributo broadcaster
public String getBroadcaster(){
return this.broadcaster;
}
//método para retornar o atributo streaming
public String getStreaming(){
return this.streaming;
}
//método para retornar o atributo seasons
public int getSeasons(){
return this.seasons;
}
//método para retornar o atributo episodes
public int getEpisodes(){
return this.episodes;
}
//método para clonar a classe
public Serie clone(){
Serie resp = new Serie();
resp.name = this.name;
resp.format = this.format;
resp.duration = this.duration;
resp.country = this.country;
resp.language = this.language;
resp.broadcaster = this.broadcaster;
resp.streaming = this.streaming;
resp.seasons = this.seasons;
resp.episodes = this.episodes;
return resp;
}
//método para printar a classe
public void printClass(){
System.out.println(this.name + " " + this.format + " " + this.duration + " " + this.country + " " + this.language + " " + this.broadcaster + " " +
this.streaming + " " + this.seasons + " " + this.episodes);
}
//método para tratar a linha, deixar apenas números e converter o retorno de String para Integer
public int justInt(String line){
String resp = "";
for(int i = 0; i < line.length(); i++){
if(line.charAt(i) >= '0' && line.charAt(i) <= '9'){ //caso o caracter seja um número ele é concatenado a variável resp
resp += line.charAt(i);
} else { //caso seja outro caracter, o i recebe o valor da condição de parada e o método de repetição é encerrado
i = line.length();
}
}
return Integer.parseInt(resp); //conversão da string resp para número inteiro a ser retornado
}
//método para a remoção das tags da linha lida do arquivo para retornar apenas o que é desejado
public String removeTags(String line){
String resp = "";
int i = 0;
while(i < line.length()){ //enquanto i for menor que o tamanho da String linha
if(line.charAt(i) == '<'){ // é testado para verificar se o contador i ainda está dentro das tags
i++;
while(line.charAt(i) != '>') i++; //ao encontrar o sinal de fechamento das tags o laço de repetição é encerrado
} else if(line.charAt(i) == '&'){ //mesmo tratamento de cima mas para outras exceções presentes em alguns outros arquivos
i++;
while(line.charAt(i) != ';') i++;
} else { //o que estiver fora das tags é concatenado a String resp a ser retornada
resp += line.charAt(i);
}
i++;
}
//System.out.println(resp);
return resp;
}
//método para tratar o nome do arquivo e retornar o nome da série
public String searchName(String fileName){
String resp = "";
for(int i = 0; i < fileName.length(); i++){
if(fileName.charAt(i) == '_'){ //caso o caracter na posição i seja igual ao '_' a variável resp recebe um espaço em branco
resp += ' ';
} else { //caso não tenha espaço em branco o caracter é concatenado à string resp
resp += fileName.charAt(i);
}
}
return resp.substring(0, resp.length()-5); //retorno da substring resp retirando os 5 últimos caracteres relacionados à extensão do arquivo
}
//método para leitura do arquivo .html e tratamento das linhas
public void readClass(String fileName){
String line;
String resp = "";
String file = "/tmp/series/" + fileName;
try {
FileReader fileReader = new FileReader(file); //declaração da variável fileReader que será recebida pelo bufferedReader
BufferedReader br = new BufferedReader(fileReader); //declaração do bufferedReader para leitura do arquivo
//set nome da série
this.name = searchName(fileName).trim();
//set Formato da série
while(!br.readLine().contains("Formato"));
this.format = removeTags(br.readLine());
//set duração da série
while(!br.readLine().contains("Duração"));
this.duration = removeTags(br.readLine());
//set país da série
while(!br.readLine().contains("País de origem"));
this.country = removeTags(br.readLine());
//set idioma da série
while(!br.readLine().contains("Idioma original"));
this.language = removeTags(br.readLine());
//set emissora da série
while(!br.readLine().contains("Emissora de televisão"));
this.broadcaster = removeTags(br.readLine());
//set transmissão original da série
while(!br.readLine().contains("Transmissão original"));
this.streaming = removeTags(br.readLine());
//set temporadas da série
while(!br.readLine().contains("N.º de temporadas"));
this.seasons = justInt(removeTags(br.readLine()));
//set episódios da série
while(!br.readLine().contains("N.º de episódios"));
this.episodes = justInt(removeTags(br.readLine()));
//fechamento do bufferedReader
br.close();
//Tratamento de exceções
} catch(FileNotFoundException e) {
System.out.println("Unable to open file '" + fileName + "'");
} catch(IOException e) {
System.out.println("Error reading file '" + fileName + "'");
}
}
}

View File

@ -1,180 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_FIELD_SIZE 100
typedef struct {
char nome[MAX_FIELD_SIZE];
char formato[MAX_FIELD_SIZE];
char duracao[MAX_FIELD_SIZE];
char pais[MAX_FIELD_SIZE];
char idioma[MAX_FIELD_SIZE];
char emissora[MAX_FIELD_SIZE];
char transmissao[MAX_FIELD_SIZE];
int num_temporadas;
int num_episodios;
} Serie;
char *remove_line_break(char *line) {
while (*line != '\r' && *line != '\n') line++;
*line = '\0';
return line;
}
char *freadline(char *line, int max_size, FILE *file) {
return remove_line_break(fgets(line, max_size, file));
}
char *readline(char *line, int max_size) {
return freadline(line, max_size, stdin);
}
void print_serie(Serie *serie) {
printf("%s %s %s %s %s %s %s %d %d\n",
serie->nome,
serie->formato,
serie->duracao,
serie->pais,
serie->idioma,
serie->emissora,
serie->transmissao,
serie->num_temporadas,
serie->num_episodios
);
}
// Retorna o tamanho em bytes de um arquivo.
long tam_arquivo(FILE *file) {
fseek(file, 0L, SEEK_END);
long size = ftell(file);
rewind(file);
return size;
}
// Retorna todo o conteúdo do arquivo numa string.
char *ler_html(char filename[]) {
FILE *file = fopen(filename, "r");
if (!file) {
fprintf(stderr, "Falha ao abrir arquivo %s\n", filename);
exit(1);
}
long tam = tam_arquivo(file);
char *html = (char *) malloc(sizeof(char) * (tam + 1));
fread(html, 1, tam, file);
fclose(file);
html[tam] = '\0';
return html;
}
/**
* @brief Extrai os textos de uma tag html.
*
* @param html Ponteiro para o caractere que abre a tag '<'.
* @param texto Ponteiro para onde o texto deve ser colocado.
*
* @return Ponteiro para o texto extraído.
*/
char *extrair_texto(char *html, char *texto) {
char *start = texto;
int contagem = 0;
while (*html != '\0') {
if (*html == '<') {
if (
(*(html + 1) == 'p') ||
(*(html + 1) == 'b' && *(html + 2) == 'r') ||
(*(html + 1) == '/' && *(html + 2) == 'h' && *(html + 3) == '1') ||
(*(html + 1) == '/' && *(html + 2) == 't' && *(html + 3) == 'h') ||
(*(html + 1) == '/' && *(html + 2) == 't' && *(html + 3) == 'd')
) break;
else contagem++;
}
else if (*html == '>') contagem--;
else if (contagem == 0 && *html != '"') {
if (*html == '&') html = strchr(html, ';');
else if (*html != '\r' && *html != '\n') *texto++ = *html;
}
html++;
}
*texto = '\0';
return *start == ' ' ? start + 1 : start;
}
/**
* @brief o HTML da série e popula os campos da struct.
*
* @param serie Struct Serie que vai receber os dados.
* @param html String contendo todo o HTML do arquivo.
*/
void ler_serie(Serie *serie, char *html) {
char texto[MAX_FIELD_SIZE];
char *ptr = strstr(html, "<h1");
extrair_texto(ptr, texto);
char *parenteses_ptr = strchr(texto, '(');
if (parenteses_ptr != NULL) *(parenteses_ptr - 1) = '\0';
strcpy(serie->nome, texto);
ptr = strstr(ptr, "<table class=\"infobox_v2\"");
ptr = strstr(ptr, "Formato");
ptr = strstr(ptr, "<td");
strcpy(serie->formato, extrair_texto(ptr, texto));
ptr = strstr(ptr, "Duração");
ptr = strstr(ptr, "<td");
strcpy(serie->duracao, extrair_texto(ptr, texto));
ptr = strstr(ptr, "País de origem");
ptr = strstr(ptr, "<td");
strcpy(serie->pais, extrair_texto(ptr, texto));
ptr = strstr(ptr, "Idioma original");
ptr = strstr(ptr, "<td");
strcpy(serie->idioma, extrair_texto(ptr, texto));
ptr = strstr(ptr, "Emissora de televisão original");
ptr = strstr(ptr, "<td");
strcpy(serie->emissora, extrair_texto(ptr, texto));
ptr = strstr(ptr, "Transmissão original");
ptr = strstr(ptr, "<td");
strcpy(serie->transmissao, extrair_texto(ptr, texto));
ptr = strstr(ptr, "N.º de temporadas");
ptr = strstr(ptr, "<td");
sscanf(extrair_texto(ptr, texto), "%d", &serie->num_temporadas);
ptr = strstr(ptr, "N.º de episódios");
ptr = strstr(ptr, "<td");
sscanf(extrair_texto(ptr, texto), "%d", &serie->num_episodios);
}
#define MAX_LINE_SIZE 250
#define PREFIXO "/tmp/series/"
// #define PREFIXO "../entrada e saida/tp02/series/"
int isFim(char line[]) {
return line[0] == 'F' && line[1] == 'I' && line[2] == 'M';
}
int main() {
Serie serie;
size_t tam_prefixo = strlen(PREFIXO);
char line[MAX_LINE_SIZE];
strcpy(line, PREFIXO);
readline(line + tam_prefixo, MAX_LINE_SIZE);
while (!isFim(line + tam_prefixo)) {
char *html = ler_html(line);
ler_serie(&serie, html);
free(html);
print_serie(&serie);
readline(line + tam_prefixo, MAX_LINE_SIZE);
}
return EXIT_SUCCESS;
}