-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
926 lines (656 loc) · 39.4 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
<!DOCTYPE html>
<html lang="" xml:lang="">
<head>
<title>Introdução a Web Scraping com R</title>
<meta charset="utf-8" />
<meta name="author" content="Jodavid Ferreira" />
<script src="libs/header-attrs/header-attrs.js"></script>
<link rel="stylesheet" href="css/jodavid.css" type="text/css" />
<link rel="stylesheet" href="css/mmp.css" type="text/css" />
<link rel="stylesheet" href="css/mmp-fonts.css" type="text/css" />
</head>
<body>
<textarea id="source">
class: center, middle, inverse, title-slide
# Introdução a Web Scraping com R
### Jodavid Ferreira
### HartB Group
### 19.09.2021
---
layout: true
<div class="my-footer"><span>
<a href="http://jodavid.github.io">Jodavid Ferreira</a> - e-mail: <a href="mailto:jodavid@protonmail.com">jodavid@protonmail.com</a> |
LinkedIn: <a href="https://www.linkedin.com/in/jodavidferreira/">jodavidferreira</a>
</span></div>
---
<br/>
# O que é Web Scraping?
<br/>
* O **Web Scraping** é uma área da **Text Mining (Mineração de Texto)** ;
<br/><br/>
### O que é Mineração de Texto?
Segundo o Livro '`Text Mining in Practice with R`':
<br/>
* "Mineração de texto é o processo de **destilar**<sup>1</sup> **insights** de texto".
.footnote[
[1] A destilação é uma técnica de separação.
]
---
### Onde a mineração de texto se encaixa?
<br/>
* Para **acadêmicos**, pode auxiliar na compreensão de transcrições qualitativas ou em um estudo da linguagem;
<br/>
* Para **empresas**, pode render informações interessantes que auxiliarão na modelagem preditiva por exemplo;
<br/>
* Aos **profissionais de marketing**, podem auxiliar na criação de textos, fornecendo recomendações precisas para sua organização.
<!--isso porque através de análises de textos externos, eles podem criar os seus fornecendo recomendações precisas para sua organização.-->
<br/>
* Então, a **mineração de texto** pode ser usada em qualquer decisão baseada em dados, onde o texto se encaixa naturalmente como uma entrada.
---
# Pacote `rvest`
<br/>
<br/>
<div class="figure" style="text-align: center">
<img src="https://raw.githubusercontent.com/tidyverse/rvest/master/man/figures/logo.png" alt="&lt;center&gt;&lt;b&gt;Logo - rvest &lt;/center&gt;&lt;/b&gt;" width="20%" />
<p class="caption"><center><b>Logo - rvest </center></b></p>
</div>
<br/>
`rvest` ajuda você a extrair (ou colher) dados de páginas da web.
Ele foi projetado para funcionar com *magrittr* (pacote responsável pelo operador pipe *%>%*) para facilitar a expressão de tarefas comuns de web scraping, inspiradas em bibliotecas como a `beautiful soup` e `RoboBrowser`.
<!--
Se você estiver copiando várias páginas, recomendo fortemente o uso de rvest em conjunto com educado. O pacote educado garante que você respeite o robots.txt e não martele o site com muitas solicitações.
-->
---
# O que é HTML e CSS ?
* **HTML** (HyperText Markup Language - Linguagem de Marcação de Hipertexto) - é uma linguagem de marcação usada para estruturar uma página web.
* **CSS** (Cascading Style Sheets - Folha de Estilo em Cascata) - é usado para estilizar os elementos escritos no *HTML*.
### O que precisamos saber ?
Em **HTML** e **CSS**, existe a possibilidade de aplicar estilos através de 'class' e 'id';
* **HTML** :
* *class* : é o atributo global formado por uma lista das classes de um elemento, separada por espaços.
<!-- Classes permitem a CSS e Javascript selecionar e acessar elementos específicos através dos seletores de classe ou funções como o método DOM. -->
* *id* : define um identificador exclusivo (ID) que deve ser único por todo o documento.
<!--Seu objetivo é identificar o elemento ao navegar por âncoras (usando um identificador de fragmento), quando utilizar scripts ou estilizando (com CSS).-->
* **CSS**: usado para personalizar a parte visual dos sites.
---
# Instalando o `rvest`
<br/>
Instalando o `rvest` através do `devtools`
<br/>
```r
install.packages("devtools")
library(devtools)
devtools::install_github("tidyverse/rvest")
```
<br/>
<br/>
Lendo o pacote:
<br/>
```r
library(rvest)
```
---
## Exemplo 1: Extraindo informações do site Jarbas
### Projeto Serenata de Amor
O estudo será realizado sobre o projeto “SERENATA DE AMOR” [https://serenata.ai/](https://serenata.ai/), que é um projeto aberto no qual usa data science (ciência de dados) - a mesma tecnolgia usada por gigantes como Google, Facebook e Netflix - com o objetivo de monitorar os gastos públicos e compartilhar informações de forma acessível a todos.
* Jarbas - [https://jarbas.serenata.ai/dashboard/chamber_of_deputies/reimbursement/](https://jarbas.serenata.ai/dashboard/chamber_of_deputies/reimbursement/)
<div class="figure" style="text-align: center">
<img src="imagens/jarbas.png" alt="&lt;center&gt;&lt;b&gt;site Jarbas &lt;/center&gt;&lt;/b&gt;" width="100%" />
<p class="caption"><center><b>site Jarbas </center></b></p>
</div>
---
## Exemplo 1: Extraindo informações do site Jarbas
### Passo 1: Lendo a URL
Usando a função `read_html` do pacote `xml2` (este pacote é uma dependência do `rvest`) para ler a url.
```r
library(rvest)
url <- "https://jarbas.serenata.ai/dashboard/chamber_of_deputies/reimbursement/"
jarbas_webpage <- read_html(url)
```
---
## Exemplo 1: Extraindo informações do site Jarbas
### Passo 2: Extrair dados de classes do CSS
Class: *.field-congressperson_name*
<div class="figure" style="text-align: center">
<img src="imagens/field-congresso-name.png" alt="&lt;center&gt;&lt;b&gt;class: .field-congressperson_name &lt;/center&gt;&lt;/b&gt;" width="100%" />
<p class="caption"><center><b>class: .field-congressperson_name </center></b></p>
</div>
---
## Exemplo 1: Extraindo informações do site Jarbas
### Passo 2:
Duas funções serão utilizadas aqui:
1. *html_nodes*: Use esta função para extrair os nós que desejamos (neste caso nós com ".field-congressperson_name" como classe css)
2. *html_text*: Use esta função para extrair o texto dos nós html (neste caso, os nomes de nossos representantes)
```r
#Scraping usando classe css ‘field-congressperson_name’
jarbas_names_html <-html_nodes(jarbas_webpage, '.field-congressperson_name')
jarbas_names <- html_text(jarbas_names_html)
head(jarbas_names,3)
```
```
## [1] "Igor Kannário" "Abou Anni" "Bozzella"
```
---
## Exemplo 1: Extraindo informações do site Jarbas
### Passo 2:
```r
#SUBQUOTA TRANSLATED
jarbas_subquota_html <-html_nodes(jarbas_webpage, '.field-subquota_translated')
jarbas_subquota <- html_text(jarbas_subquota_html)
head(jarbas_subquota,3)
```
```
## [1] "Serviços postais" "Serviços postais" "Serviços postais"
```
```r
#Fornecedor
jarbas_provider_html <-html_nodes(jarbas_webpage, '.field-supplier_info')
jarbas_provider <- html_text(jarbas_provider_html)
head(jarbas_provider,3)
```
```
## [1] "CORREIOS - CAIXA DE ENCOMENDAS BÁSICA/CONVENCIONAL00.000.000/0000-07" "CORREIOS - MALA DIRETA ENDEREÇADA (POSTAL BÁSICA)00.000.000/0000-07" "CORREIOS - CARTA REGISTRADA00.000.000/0000-07"
```
```r
#Valores em Real
jarbas_value_html <-html_nodes(jarbas_webpage, '.field-value')
jarbas_value <- html_text(jarbas_value_html)
head(jarbas_value,3)
```
```
## [1] "R$ 11,30" "R$ 255,22" "R$ 96,00"
```
---
## Exemplo 1: Extraindo informações do site Jarbas
### Passo 2:
A seguir serão mostrados o valor do reembolso, eles são extraídos
em tipo de variável caracter: Ex: R$ 139,76, R$ 40,23.
Entretanto, como desejamos manipular esses números, precisamos convertê-los para tipo de variável numérica, dessa forma será utilizado a biblioteca: "*stringr*" mais especificamente a função: `str_extract`. Segue o script para conversão da variável.
```r
library(stringr)
#Conversão para tipo numérico
jarbas_value <- as.numeric(sub(",",".",
str_extract(jarbas_value,pattern = "\\-*\\d+,\\s{0,}\\d+")))
head(jarbas_value,3)
```
```
## [1] 11.30 255.22 96.00
```
---
## Exemplo 1: Extraindo informações do site Jarbas
### Passo 3: Geração de data.frame
```r
#Combinando todas as características obtidas
jarbas_names <- str_extract(jarbas_names,pattern = boundary("word"))
jarbas_df <- data.frame(
Name = jarbas_names,
Subquota = jarbas_subquota,
Provider = jarbas_provider,
Value = jarbas_value
)
#Mostrando tipo das variáveis
str(jarbas_df)
```
```
## 'data.frame': 100 obs. of 4 variables:
## $ Name : chr "Igor" "Abou" "Bozzella" "Isnaldo" ...
## $ Subquota: chr "Serviços postais" "Serviços postais" "Serviços postais" "Serviços postais" ...
## $ Provider: chr "CORREIOS - CAIXA DE ENCOMENDAS BÁSICA/CONVENCIONAL00.000.000/0000-07" "CORREIOS - MALA DIRETA ENDEREÇADA (POSTAL BÁSICA)00.000.000/0000-07" "CORREIOS - CARTA REGISTRADA00.000.000/0000-07" "CORREIOS - ENCOMENDA PAC00.000.000/0000-07" ...
## $ Value : num 11.3 255.2 96 999.3 200 ...
```
---
## Exemplo 1: Extraindo informações do site Jarbas
### Passo 4: Geração de um gráfico
Foram utilizados as 50 primeiras linhas do data.frame e uma biblioteca *ggplot2* para geração do gráfico.
```r
library(ggplot2)
jarbas_df <- jarbas_df[1:50,]
ggplot(
jarbas_df, aes(Value,Name,colour=Subquota)) +
geom_point() +
labs(title="", x ="pedidos de reembolso (R$)",
y = "deputados",colour="SUBQUOTA TRANSLATED")
```
---
<img src="index_files/figure-html/unnamed-chunk-12-1.png" style="display: block; margin: auto;" />
---
## Exemplo 2: Texto de um WebSite
Neste segundo exemplo vamos obter o texto de um site e analisá-lo.
* Site El País (categoria de Tecnologia) - [https://brasil.elpais.com/brasil/2021-01-26/todos-os-brasileiros-estao-com-seus-dados-a-venda-e-ha-muito-pouco-o-que-se-pode-fazer-para-se-proteger.html](https://brasil.elpais.com/brasil/2021-01-26/todos-os-brasileiros-estao-com-seus-dados-a-venda-e-ha-muito-pouco-o-que-se-pode-fazer-para-se-proteger.html)
<div class="figure" style="text-align: center">
<img src="imagens/elpais.png" alt="&lt;center&gt;&lt;b&gt;site ElPaís &lt;/center&gt;&lt;/b&gt;" width="100%" />
<p class="caption"><center><b>site ElPaís </center></b></p>
</div>
---
## Exemplo 2: Texto de Site
### Passo 1: Lendo a URL
```r
library(rvest)
url <- "https://brasil.elpais.com/brasil/2021-01-26/todos-os-brasileiros-estao-com-seus-dados-a-venda-e-ha-muito-pouco-o-que-se-pode-fazer-para-se-proteger.html"
webpage <- read_html(url)
```
### Passo 2: Extraindo texto de Site
```r
# Passo 2:
#Scraping usando ‘p’
names_html <-html_nodes(webpage, 'p')
names <- html_text(names_html)
head(names)
```
```
## [1] "Este navegador não é mais compatível. Para visitar EL PAÍS com a melhor experiência, atualize-o para a versão mais recente ou baixe um dos seguintes navegadores compatíveis:"
## [2] "Um megavazamento de dados pessoais de 223 milhões de brasileiros tornado público na semana passada pela empresa de segurança digital PSafe pode ser o maior na história do país e tem tudo para ser a primeira prova de fogo da Autoridade Nacional de Proteção de Dados (ANPD), criada a partir da entrada em vigor da Lei Geral de Proteção de Dados (LGPD) em agosto do ano passado. Também é o primeiro incidente desta magnitude que se tem notícia no Brasil. A lista com milhões de nomes completos, CPFs e datas de nascimento —de pessoas vivas e mortas— estava disponível para download gratuito a partir de um fórum de discussão na deep web —cópias do arquivo original foram feitas e podiam ser encontradas por qualquer um a partir de buscadores de internet. Em troca de bitcoins, o perfil anônimo responsável pelo vazamento dizia ser possível obter ainda retratos, endereço, telefone, declaração do Imposto de Renda, listas de familiares, renda mensal, score de crédito e muito mais dos alvos em questão. Na terça-feira, após a repercussão do caso, o material foi retirado do ar no fórum de livre acesso com qualquer navegador, mas continua em negociação na deep web."
## [3] "Na lista há dados de gente famosa e autoridades públicas. De acordo com a PSafe, cibercriminosos também tiveram acesso a informações detalhadas sobre mais de 104 milhões de veículos e dados sigilosos de 40 milhões de empresas."
## [4] "“O vazamento é real, confirmada a autenticidade de todos os dados, é o maior vazamento da história do Brasil e certamente um dos maiores do mundo”, afirma Marco DeMello, CEO da PSafe. “Estávamos monitorando a deep web para alguns de nossos clientes e nos deparamos com milhões de CPNJs em negociação, rastreamos e chegamos na fonte”, diz. Ele afirma que a equipe de segurança da empresa entrou em contato com o hacker, que disse cobrar 100 dólares por pacotes com os registros de mil pessoas, empresas ou veículos. Ele diz não ser brasileiro e que vai vender no máximo 1 milhão de contatos para cada comprador, pois pretende ganhar dinheiro com essa base de dados por muito tempo ainda. Segundo DeMello, nas conversas o hacker diz que roubou a base dados da Serasa/Experian, empresa de análise de crédito que cria perfis dos consumidores brasileiros entre outras atividades, mas não tem como saber se isso é verdade. A mesma alegação aparece na página onde ele vende o material, assim como no nome de alguns arquivos."
## [5] "Apoie a produção de notícias como esta. Assine o EL PAÍS por 30 dias por 1 US$"
## [6] "Procurada pela reportagem através de sua assessoria de imprensa, a Serasa/Experian respondeu, após a publicação, que a empresa não é a fonte dos dados vazados. “Embora o hacker afirme que parte dos dados veio da Serasa, com base em nossa análise detalhada até este ponto, concluímos que a Serasa não é a fonte”, diz a nota enviada. “Também não vemos evidências de que nossos sistemas tenham sido comprometidos”, afirma a empresa, que ainda diz não possuir todos os dados oferecidos na internet e que está em contato com autoridades reguladoras para ajudar no caso. "
```
---
## Exemplo 2: Texto de Site
### Passo 3: Preparação dos dados
Organizando os dados para geração do gráfico da Nuvem de Tags
* `Corpus`: função que transforma vetores/listas em coleções de documentos que contêm texto.
```r
# Início do código para Nuvem de palavras
library(tm)
# -------
# Colocando as palavras em minusculos
# -------
texto <- tolower(names)
# -------
# Removendo as stopwords
texto <- removeWords(texto, stopwords(kind = "portuguese"))
# -------
```
---
### Passo 3: Preparação dos dados - cont.
```r
# Transformando em formato Corpus
texto <- Corpus(VectorSource(texto),
readerControl = list(reader = reader(VectorSource(texto)),
language = "pt"))
# -------
# Removendo as stopwords de arquivo.txt
# -------
file <- url("https://jodavid.github.io/Slide-Introdu-o-a-Web-Scrapping-com-rvest/stopwords_pt_BR.txt")
stopwords_ptBR <- read.table(file)
stopwords_ptBR <- unlist(stopwords_ptBR, use.names = FALSE)
texto <- tm_map(texto, removeWords, stopwords_ptBR)
# -------
# Descobrindo tamanho da lista
n <- length(texto)
# -------
# Removendo pontuacao
for(i in 1:n)
{
# Remover pontuacao, preservando abreviacoes
texto[[i]] <- removePunctuation(texto[[i]],
preserve_intra_word_contractions = TRUE,
preserve_intra_word_dashes = TRUE)
# Removendo quotations
texto[[i]] <- stringr::str_replace_all(texto[[i]], setNames(c('','','',''), c('“ ', '“',' ”','”')))
}
# -------
```
---
### Passo 4: Geração de um gráfico de Nuvem de Tags
Foram utilizados o data.frame e uma biblioteca *ggplot2* para geração do gráfico.
```r
library(wordcloud)
library(yarrr)
wordcloud(words = texto, min.freq = 2, random.order = TRUE,
colors = yarrr::piratepal("basel"), use.r.layout = TRUE, rot.per = 0.5)
```
---
<img src="index_files/figure-html/unnamed-chunk-19-1.png" style="display: block; margin: auto;" />
---
## Extra: Frequência das palavras
```r
#' -------
#' Transformando o arquivo 'texto' que estava no tipo Corpus para Data.frame
#' -------
textodataframe <- data.frame(text = sapply(texto, as.character),
stringsAsFactors = FALSE)
textodataframe <- textodataframe[-which(textodataframe ==""),]
#' --------------
#' Frequencia das palavras
#' --------------
frequencia_palavras <- table( textodataframe )
frequencia_ordenada_palavras <- sort( frequencia_palavras, decreasing=TRUE)
palavras <- data.frame(frequencia_ordenada_palavras)
head(palavras,6)
```
```
## textodataframe Freq
## 1 hacker responsável vazamento profissional difícil rastrear identidade origem virtualmente brasileiros dados venda internet concreto possa executivo acredita anpd ministério púbico federal polícia federal investigar história demello alerta ficar atentos movimentações atípicas conta bancária cartão crédito avisos cobranças pistas possa utilizado fraude 1
## 2 ler textos gratuitos 1
## 3 assinante 1
## 4 dados disponíveis fórum discussões começo identificados empresa segurança terça-feira semana passada extraídos fonte original 18 2018 2020 ceo psafe informações checadas amostragem reais assustador qualquer golpista comprar dados inimagináveis comprar vender veículos imóveis contrair dívidas invadir contas bancárias sistemas informatizados usam imagens abrir empresas estrago demello 1
## 5 el país conversou profissional tecnologia informação acesso material disponibilizado graça testar veracidade cerca nomes aleatórios sugeridos reportagem busca banco dados profissional voltou resultados corretos cpf data nascimento casos gênero quase baixei queria saber material verdade gente pegou dados usar intencionada pediu identificado reportagem cópia dados cometeu ilegalidade 1
## 6 lei proteção dados entregou vigor possui artigos versam incidentes segurança criação planos resposta incidentes segurança empresas entes públicos prevê sanções advertência multa faturamento anual 50 milhões reais proibição fonte vazamento continuar tratar dados sensíveis entanto punições aplicadas agosto 2021 1
```
---
## Extra: Análise de Sentimentos
**Análise de sentimentos** é a tarefa de identificar se a opinião que foi expressada em um determinado texto, é positiva ou negativa.
Na **análise de sentimento** o grande problema a ser resolvido, é a classificação do texto que está sendo analisado. A classificação consiste no processo de encontrar, através de *Machine Learning*, um modelo ou função que descreva diferentes classes de dados.
<div class="figure" style="text-align: center">
<img src="https://binds.co/img/section/faces-sentiment.png" alt="&lt;center&gt;&lt;b&gt;Análise de Sentimento&lt;/center&gt;&lt;/b&gt;" width="55%" />
<p class="caption"><center><b>Análise de Sentimento</center></b></p>
</div>
Fonte: [https://binds.co/img/section/faces-sentiment.png](https://binds.co/img/section/faces-sentiment.png)
---
## Extra: Análise de Sentimentos
Uma das formas mais antigas para tratar desse problema é por meio do algoritmo de Naive Bayes que é um classificador probabilístico, e parte da premissa que há independência entre as características (variáveis - features) de um modelo, uu seja, ele recebe o nome de “naive” (ingênuo) porque desconsidera a correlação entre as variáveis (features).
Post: [https://jodavid.github.io/post/2021-06-06-scraping-de-texto-com-an%C3%A1lise-de-sentimento-em-r/](https://jodavid.github.io/post/2021-06-06-scraping-de-texto-com-an%C3%A1lise-de-sentimento-em-r/)
<div class="figure" style="text-align: center">
<img src="imagens/sentimentBR.png" alt="&lt;center&gt;&lt;b&gt;sentimentBR&lt;/center&gt;&lt;/b&gt;" width="75%" />
<p class="caption"><center><b>sentimentBR</center></b></p>
</div>
---
# Pacote `sentimentBR`
<br/>
<br/>
<div class="figure" style="text-align: center">
<img src="https://jodavid.github.io/sentimentBR/reference/figures/logo.png" alt="&lt;center&gt;&lt;b&gt;Logo - sentimentBR &lt;/center&gt;&lt;/b&gt;" width="20%" />
<p class="caption"><center><b>Logo - sentimentBR </center></b></p>
</div>
<br/>
Link: [https://jodavid.github.io/sentimentBR/](https://jodavid.github.io/sentimentBR/)
Este é um pacote inicial com o intuito de juntar as funções e dicionários cada vez mais em português para que seja possível realizar uma **Análise de Sentimento** cada vez mais eficiente e com boa confiabilidade.
---
# Instalando o `sentimentBR`
```r
# Instalação utilizando o pacote devtools
install.packages("devtools")
# Instalação do pacote de dependência
install.packages("Rstem", repos = "http://www.omegahat.net/R")
# Instação do pacote sentimentBR
devtools::install_github("jodavid/sentimentBR")
```
Lendo o pacote
```r
# Lendo o pacote
library(sentimentBR)
```
---
## Extra: Análise de Sentimentos
A Classificação será feita no DataFrame das frases,
vamos retornar a matriz:
A matriz de dados está nomeada como `texto` no slide 17.
```r
# -------
# Pacotes Necessários
library(sentimentBR)
library(lexiconPT)
# -------
# -------
# Transformando o arquivo 'texto' que estava no tipo Corpus para Data.frame
textodataframe <- data.frame(text = sapply(texto, as.character), stringsAsFactors = FALSE)
# -------
```
---
## Extra: Análise de Sentimentos
Usando a função classify_emotion para classificar as emoções. É possível obter seis níveis de emoções: **RAIVA, DESGOSTO, MEDO, ALEGRIA, TRISTEZA, SURPRESA, CONFIANÇA, POSITIVA, NEGATIVA, ANTECIPAÇÃO**.
```r
# -------
# Classificando as emocoes de cada paragrafo
emotions <- classify_emotion(textColumns = textodataframe, algorithm = 'bayes', lang = "pt")
emotions
```
```
## RAIVA DESGOSTO MEDO ALEGRIA TRISTEZA SURPRESA CONFIANÇA POSITIVA NEGATIVA ANTECIPAÇÃO BEST_FIT
## [1,] "2.29534107053581" "2.61502587407376" "2.23117171201856" "16.6710820846312" "9.6244348067824" "3.20281253897588" "9.6244348067824" "9.6244348067824" "1.51551065080706" "9.6244348067824" "alegria"
## [2,] "46.2699034880154" "16.633843739491" "31.8042240910739" "30.7643766403287" "31.3420797281218" "22.4676793423954" "59.4335096900736" "87.0831171047051" "50.1690555866591" "50.0176990455856" "positiva"
## [3,] "2.29534107053581" "2.61502587407376" "9.6244348067824" "9.6244348067824" "2.3852198330026" "3.20281253897588" "9.6244348067824" "17.3703030365747" "17.7333589627577" "9.6244348067824" "negativa"
## [4,] "24.2826222792756" "37.6620705376169" "46.5907502806016" "16.6710820846312" "9.6244348067824" "22.4676793423954" "52.3179275638891" "71.5913806451205" "82.6047522105605" "16.3566455132496" "negativa"
## [5,] "9.6244348067824" "2.61502587407376" "2.23117171201856" "2.57778752893365" "2.3852198330026" "3.20281253897588" "2.50885268059795" "1.87856657699013" "9.6244348067824" "2.8922241003152" "raiva"
## [6,] "31.6117160155222" "16.633843739491" "24.4109609963101" "9.6244348067824" "16.8636497805622" "16.0460570745889" "2.50885268059795" "9.6244348067824" "25.8422831187331" "16.3566455132496" "raiva"
## [7,] "9.6244348067824" "2.61502587407376" "24.4109609963101" "9.6244348067824" "9.6244348067824" "16.0460570745889" "9.6244348067824" "1.87856657699013" "42.0601314306838" "9.6244348067824" "negativa"
## [8,] "24.2826222792756" "23.6432526721997" "17.0176979015462" "16.6710820846312" "24.102864754342" "16.0460570745889" "30.9711811853358" "56.099644185536" "25.8422831187331" "36.5532776326512" "positiva"
## [9,] "31.6117160155222" "16.633843739491" "39.1974871858378" "16.6710820846312" "2.3852198330026" "9.6244348067824" "16.7400169329669" "25.1161712663669" "33.9512072747084" "36.5532776326512" "medo"
## [10,] "24.2826222792756" "16.633843739491" "24.4109609963101" "23.7177293624799" "31.3420797281218" "9.6244348067824" "23.8555990591513" "48.3537759557437" "58.2779797426344" "36.5532776326512" "negativa"
## [11,] "38.9408097517688" "9.6244348067824" "31.8042240910739" "16.6710820846312" "16.8636497805622" "9.6244348067824" "45.2023454377047" "40.6079077259515" "66.3869038986098" "9.6244348067824" "negativa"
## [12,] "16.953528543029" "2.61502587407376" "9.6244348067824" "2.57778752893365" "2.3852198330026" "16.0460570745889" "9.6244348067824" "9.6244348067824" "25.8422831187331" "9.6244348067824" "negativa"
## [13,] "24.2826222792756" "23.6432526721997" "17.0176979015462" "23.7177293624799" "16.8636497805622" "16.0460570745889" "23.8555990591513" "32.8620394961592" "25.8422831187331" "23.0888562197168" "positiva"
## [14,] "2.29534107053581" "2.61502587407376" "2.23117171201856" "2.57778752893365" "2.3852198330026" "9.6244348067824" "2.50885268059795" "1.87856657699013" "9.6244348067824" "2.8922241003152" "surpresa"
## [15,] "2.29534107053581" "2.61502587407376" "2.23117171201856" "2.57778752893365" "2.3852198330026" "3.20281253897588" "2.50885268059795" "1.87856657699013" "1.51551065080706" "2.8922241003152" "surpresa"
## [16,] "2.29534107053581" "2.61502587407376" "9.6244348067824" "9.6244348067824" "2.3852198330026" "9.6244348067824" "2.50885268059795" "1.87856657699013" "9.6244348067824" "2.8922241003152" "medo"
## [17,] "2.29534107053581" "2.61502587407376" "2.23117171201856" "2.57778752893365" "2.3852198330026" "3.20281253897588" "2.50885268059795" "1.87856657699013" "1.51551065080706" "2.8922241003152" "surpresa"
## [18,] "2.29534107053581" "2.61502587407376" "2.23117171201856" "2.57778752893365" "2.3852198330026" "3.20281253897588" "2.50885268059795" "1.87856657699013" "1.51551065080706" "2.8922241003152" "surpresa"
## [19,] "2.29534107053581" "2.61502587407376" "2.23117171201856" "2.57778752893365" "2.3852198330026" "3.20281253897588" "2.50885268059795" "1.87856657699013" "1.51551065080706" "2.8922241003152" "surpresa"
```
---
## Extra: Análise de Sentimentos
```r
# -------
# Quantos Parágrafos
nrow(emotions)
```
```
## [1] 19
```
```r
# -------
# Tabela das classificações
table(emotions[,11])
```
```
##
## alegria medo negativa positiva raiva surpresa
## 1 2 6 3 2 5
```
Calculando as Polaridades
```r
# -------
# Classificando a polaridade de cada paragrafi
polarities <- classify_polarity(textColumns = textodataframe, algorithm = "bayes")
head(polarities,1)
```
```
## POS NEG POS/NEG BEST_FIT
## [1,] "1.03127774142571" "0.445453222112551" "2.31512017476245" "positive"
```
---
## Extra: Análise de Sentimentos
Neste caso também a classificação é obtida na última coluna denominada de `BEST_FIT`.
```r
# -------
# Transformando os resultados em data.frame
df <- data.frame(paragrafos = textodataframe,
emocoes = emotions[,'BEST_FIT'],
polaridades = polarities[,'BEST_FIT'])
# Transformando os 'NA' em 'N.A.'
df[is.na(df)] <- "N.A."
# -------
```
---
### Criando um gráfico de Barras com as polaridades
```r
# -------
# Pacote Necessário
library(ggplot2)
# -------
ggplot(df, aes(polaridades,fill=polaridades)) +
geom_bar() +
labs(title="", x ="Polaridades",
y = "Quantidades") +
theme_minimal()
```
<img src="index_files/figure-html/unnamed-chunk-31-1.png" style="display: block; margin: auto;" />
---
### Criando um gráfico de Barras e Setores com 'emocoes'
```r
# -------
ggplot(df, aes(emocoes,fill=emocoes)) +
geom_bar() +
labs(title="", x ="Emoções",
y = "Quantidades") +
theme_minimal()
```
<img src="index_files/figure-html/unnamed-chunk-32-1.png" style="display: block; margin: auto;" />
---
## Gráfico de Nuvem de tags com polaridades
```r
# -------
# Pacote Necessário
library(dplyr)
# -------
# Dividindo o texto nas polaridades
polaridades_cat <- unique(df$polaridades)
# -------
df2 <- t( sapply(1:length(polaridades_cat),function(i){
polaridade <- summarise(df,
texto2 = paste(df$text[which(df$polaridades==polaridades_cat[i])],
collapse = " "));
return(c(polaridades = polaridades_cat[i],
pasted = c(polaridade$texto2)))
}) )
# -------
corpus <- Corpus(VectorSource(df2[,2]))
corpus <- tm_map(corpus, removeNumbers)
tdm <- TermDocumentMatrix(corpus)
tdm <- as.matrix(tdm)
colnames(tdm) <- unique(df2[,1])
# -------
```
---
## Gráfico de Nuvem de tags com polaridades
```r
# -------
# Gerando Gráfico
comparison.cloud(tdm,
colors = yarrr::piratepal("basel"),
scale = c(3,.5),random.order = F)
```
<img src="index_files/figure-html/unnamed-chunk-34-1.png" style="display: block; margin: auto;" />
---
# Script R
Segue abaixo o link para o Script **R** ulitizado:
[Script R - Clique Aqui!](https://raw.githubusercontent.com/Jodavid/Slide-Introdu-o-a-Web-Scrapping-com-rvest/master/Script%20-%20Introducao-.R)
# Fontes
* Slide produzido com Rmarkdown, com template
`Xaringan`: [https://github.com/yihui/xaringan](https://github.com/yihui/xaringan).
* Livro: `Text Mining in Practice with R`;
* [https://github.com/tidyverse/rvest](https://github.com/tidyverse/rvest)
* [https://brasil.elpais.com/brasil/2021-01-26/todos-os-brasileiros-estao-com-seus-dados-a-venda-e-ha-muito-pouco-o-que-se-pode-fazer-para-se-proteger.html](https://brasil.elpais.com/brasil/2021-01-26/todos-os-brasileiros-estao-com-seus-dados-a-venda-e-ha-muito-pouco-o-que-se-pode-fazer-para-se-proteger.html)
* [http://www.cienciaedados.com/analise-de-sentimentos-e-machine-learning/#:~:text=An%C3%A1lise%20de%20sentimentos%20%C3%A9%20a,texto%2C%20%C3%A9%20positiva%20ou%20negativa.](http://www.cienciaedados.com/analise-de-sentimentos-e-machine-learning/#:~:text=An%C3%A1lise%20de%20sentimentos%20%C3%A9%20a,texto%2C%20%C3%A9%20positiva%20ou%20negativa.)
</textarea>
<style data-target="print-only">@media screen {.remark-slide-container{display:block;}.remark-slide-scaler{box-shadow:none;}}</style>
<script src="https://remarkjs.com/downloads/remark-latest.min.js"></script>
<script>var slideshow = remark.create({
"highlightStyle": "github",
"highlightLines": true,
"countIncrementalSlides": false
});
if (window.HTMLWidgets) slideshow.on('afterShowSlide', function (slide) {
window.dispatchEvent(new Event('resize'));
});
(function(d) {
var s = d.createElement("style"), r = d.querySelector(".remark-slide-scaler");
if (!r) return;
s.type = "text/css"; s.innerHTML = "@page {size: " + r.style.width + " " + r.style.height +"; }";
d.head.appendChild(s);
})(document);
(function(d) {
var el = d.getElementsByClassName("remark-slides-area");
if (!el) return;
var slide, slides = slideshow.getSlides(), els = el[0].children;
for (var i = 1; i < slides.length; i++) {
slide = slides[i];
if (slide.properties.continued === "true" || slide.properties.count === "false") {
els[i - 1].className += ' has-continuation';
}
}
var s = d.createElement("style");
s.type = "text/css"; s.innerHTML = "@media print { .has-continuation { display: none; } }";
d.head.appendChild(s);
})(document);
// delete the temporary CSS (for displaying all slides initially) when the user
// starts to view slides
(function() {
var deleted = false;
slideshow.on('beforeShowSlide', function(slide) {
if (deleted) return;
var sheets = document.styleSheets, node;
for (var i = 0; i < sheets.length; i++) {
node = sheets[i].ownerNode;
if (node.dataset["target"] !== "print-only") continue;
node.parentNode.removeChild(node);
}
deleted = true;
});
})();
(function() {
"use strict"
// Replace <script> tags in slides area to make them executable
var scripts = document.querySelectorAll(
'.remark-slides-area .remark-slide-container script'
);
if (!scripts.length) return;
for (var i = 0; i < scripts.length; i++) {
var s = document.createElement('script');
var code = document.createTextNode(scripts[i].textContent);
s.appendChild(code);
var scriptAttrs = scripts[i].attributes;
for (var j = 0; j < scriptAttrs.length; j++) {
s.setAttribute(scriptAttrs[j].name, scriptAttrs[j].value);
}
scripts[i].parentElement.replaceChild(s, scripts[i]);
}
})();
(function() {
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
if (/^(https?:)?\/\//.test(links[i].getAttribute('href'))) {
links[i].target = '_blank';
}
}
})();
// adds .remark-code-has-line-highlighted class to <pre> parent elements
// of code chunks containing highlighted lines with class .remark-code-line-highlighted
(function(d) {
const hlines = d.querySelectorAll('.remark-code-line-highlighted');
const preParents = [];
const findPreParent = function(line, p = 0) {
if (p > 1) return null; // traverse up no further than grandparent
const el = line.parentElement;
return el.tagName === "PRE" ? el : findPreParent(el, ++p);
};
for (let line of hlines) {
let pre = findPreParent(line);
if (pre && !preParents.includes(pre)) preParents.push(pre);
}
preParents.forEach(p => p.classList.add("remark-code-has-line-highlighted"));
})(document);</script>
<script>
slideshow._releaseMath = function(el) {
var i, text, code, codes = el.getElementsByTagName('code');
for (i = 0; i < codes.length;) {
code = codes[i];
if (code.parentNode.tagName !== 'PRE' && code.childElementCount === 0) {
text = code.textContent;
if (/^\\\((.|\s)+\\\)$/.test(text) || /^\\\[(.|\s)+\\\]$/.test(text) ||
/^\$\$(.|\s)+\$\$$/.test(text) ||
/^\\begin\{([^}]+)\}(.|\s)+\\end\{[^}]+\}$/.test(text)) {
code.outerHTML = code.innerHTML; // remove <code></code>
continue;
}
}
i++;
}
};
slideshow._releaseMath(document);
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML';
if (location.protocol !== 'file:' && /^https?:/.test(script.src))
script.src = script.src.replace(/^https?:/, '');
document.getElementsByTagName('head')[0].appendChild(script);
})();
</script>
</body>
</html>