-
Notifications
You must be signed in to change notification settings - Fork 0
/
Namenserkennung.R
1477 lines (1138 loc) · 56.2 KB
/
Namenserkennung.R
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
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
################################################
#### Capstone Course Media Representation ####
#### Compounding the Names to single tokens ####
################################################
#### Preparations ####
# Cleaning
rm(list=ls())
# define stringsAsFactors = FALSE as default
options(stringsAsFactors = FALSE)
# Loading Packages
library(tidyverse)
library(readtext)
library(readxl)
library(doParallel)
library(foreach)
library(tictoc)
# Loading Data
# Cantonal Data
candidatesKW <- read.csv2("~/capstone_share/Data_Names/Data_BfS/KW_KANDIDATENSTIMMEN_KT.csv", fileEncoding = "ISO-8859-1")
# National Data
candidatesNR <- read.csv2("~/capstone_share/Data_Names/Data_BfS/NRW_KANDIDATENSTIMMEN_KT.csv", fileEncoding = "ISO-8859-1")
# MPs
membersParliament <- read_excel("~/capstone_share/Data_Names/Parlamentsdienste/Ratsmitglieder_1848_DE.xlsx")
##### Getting Candidate Names ####
# constructing year for KW
candidatesKW$year <- candidatesKW$voting_id%>%
str_extract(pattern="[:digit:]{4}")%>%
as.numeric()
# constructing year for NR
candidatesNR$year <- candidatesNR$voting_id%>%
str_extract(pattern="[:digit:]{4}")%>%
as.numeric()
# constructing year for MPs
membersParliament$year_joined <- membersParliament$DateJoining%>%
str_extract(pattern="[:digit:]{4}")%>%
as.numeric()
membersParliament$year_left <- membersParliament$DateLeaving%>%
str_extract(pattern="[:digit:]{4}")%>%
as.numeric()
membersParliament$year_left[is.na(membersParliament$year_left)] <- 9999
# recode year of birth to something useful
membersParliament$geburtsjahr <- membersParliament$DateOfBirth%>%
str_extract(pattern="[:digit:]{4}")%>%
as.numeric()
candidatesKW$geburtsjahr <- candidatesKW$geburtsjahr%>%
str_extract(pattern="[:digit:]{4}")%>%
as.numeric()
candidatesNR$geburtsjahr <- candidatesNR$geburtsjahr%>%
str_extract(pattern="[:digit:]{4}")%>%
as.numeric()
# filter relevant candidates
# election year, and being elected
relevantcandidatesKW <- dplyr::filter(candidatesKW, year >= 2008 & gewaehlt == 1)
relevantcandidatesNR <- dplyr::filter(candidatesNR, year >= 2010 & gewaehlt == 1)
relevantMPs <- dplyr::filter(membersParliament, year_left >= 2000) # everyone that left since 2000
# select relevant variables: last Name, first Name, sex, party name, year of birth
namKW <- relevantcandidatesKW %>% select(NAME, vorname, geschlecht, parteiname, geburtsjahr)
namNR <- relevantcandidatesNR %>% select(NAME, vorname, geschlecht, parteiname, geburtsjahr)
namMP <- relevantMPs %>% select(LastName, FirstName, GenderAsString, PartyAbbreviation, geburtsjahr)
# recode Gender
namMP$GenderAsString <- recode(namMP$GenderAsString, "m" = 2, "f" = 1)
# make the column names uniform
names(namMP) <- names(namNR)
# combining national, cantonal and parliamentary data
nam<- namKW %>% rbind(namMP) %>% rbind(namNR)
#recoding party names
unique(nam$parteiname) # All Party names
nam$parteiname <- car::recode(nam$parteiname, "
c('SVP/UDC', 'SVP/UDC')= 'SVP';
c('SP/PS', 'SP') = 'SP';
c('CVP/PDC', 'CVP', 'CVPO') = 'CVP';
c('FDP/PLR (PRD)', 'FDP', 'FDP-Liberale') = 'FDP';
c('GPS/PES', 'GPS','GB') = 'GPS';
c('EVP/PEV', 'EVP') = 'EVP';
c('EDU/UDF', 'EDU') = 'EDU';
c('SD/DS', 'SD') = 'SD';
c('GLP/PVL', 'glp') = 'GLP';
c('BDP/PBD', 'BDP') = 'BDP';
c('CSPO', 'csp-ow', 'CSP', 'CSP/PCS') = 'CSP'
")
unique(nam$parteiname)# All Party names -> further suggetions?
table(nam$parteiname)
#remove errors in encoding which are displayed as ? or similar
nam$vorname <- nam$vorname%>%
str_replace_all("\\.", replacement = " ")%>%
str_replace_all(pattern = "[:punct:]", replacement = ".")%>%
str_squish()
nam$NAME <- nam$NAME%>%
str_replace_all("\\.", replacement = " ")%>%
str_replace_all(pattern = "[:punct:]", replacement = ".")%>%
str_squish()
# create full name
nam$name <- paste(nam$vorname, nam$NAME)
# create dictionary entry
nam$dict <- paste(nam$vorname, nam$NAME, sep = "_")%>%
str_replace_all("\\s|[:punct:]", "_")
# preparing the regex: taking only the first first name
vornamen <- nam$vorname%>%
str_split(pattern = "\\s", simplify = T)
# splitting the last name up
nachnamen1 <-nam$NAME%>%
str_split(pattern = "\\s|[:punct:]", simplify = T)
# get length of names
nachnamencount <- nachnamen1%>%
apply(MARGIN = 2, FUN = str_length)
# delete all names which consist only of one letter or are titles e.g. "von"
nachnamen1[nachnamencount<2|nachnamen1=="de"|nachnamen1=="De"|nachnamen1=="von"|nachnamen1=="Von"|nachnamen1=="la"|nachnamen1=="La"|nachnamen1=="der"|nachnamen1=="Der"|nachnamen1=="Van"|nachnamen1=="van"|nachnamen1=="di"|nachnamen1=="da"|nachnamen1=="Di"|nachnamen1=="Da"] <- ""
# create regex, which lists every part of a name as part separated by |
nachnamen1 <- nachnamen1%>%
apply(1, FUN = paste0, collapse = "|")%>%
str_replace_all(pattern = "\\|{2,}", replacement = "|")%>%
str_remove_all(pattern = "\\|{2,4}|(^\\|)|(\\|$)")
# create regex, which takes the whole last name, parts separated by .
nachnamen2 <-nam$NAME%>%
str_split(pattern = "\\s|[:punct:]")%>%
sapply(FUN = paste0, collapse = ".")%>%
str_replace_all(pattern = "(\\|){2}", replacement = "|")%>%
str_remove_all(pattern = "\\.{2,4}|(^\\|)|(\\|$)")
# paste the two regexes behind each other in the case that they differ
nachnamen <- ifelse(nachnamen1==nachnamen2, nachnamen1,
paste0(nachnamen1, "|", nachnamen2))
# create the final search regex
nam$Regex_Bruno <- paste0("(",
vornamen[ ,1],
")",
".{0,15}?",
"[^_\\-]",
"(",
nachnamen,
")(s)?(?![[:alpha:]_\\-])"
)
# get unique versions of the names
namunique <- unique(nam)
# test the Regex
vec_testsring <- c("Bundesrat Ueli Maurer",
"Bundesrätin Karin Keller-Sutter",
"Die Konditorin Karin Sutter",
"Nationalrätin Susanne Leutenegger Oberholzer",
"Kantonalpolitikerin Susanne Oberholzer",
"Susanne_Oberholzer_Glatt Susanne Oberholzer Susanne_Leutenegger_Oberholzer Susanne Leutenegger Oberholzer",
"Die Moderatorin Susanne Wille")
df_test_regexes <- namunique %>%
filter(dict%in%c("Ueli_Maurer", "Karin_Keller_Sutter", "Susanne_Oberholzer", "Susanne_Leutenegger_Oberholzer"))%>%
arrange(dict)
vec_regexes <- df_test_regexes$dict
names(vec_regexes) <- df_test_regexes$Regex_Bruno
vec_regexes
str_replace_all(string = vec_testsring, vec_regexes)
# Seems not to work quite fine
# remove duplicate entries, if they differ only in the year of birth and one of them is NA
namunique <- namunique %>%
group_by(NAME, vorname, geschlecht, parteiname, name, dict, Regex_Bruno) %>%
filter(if(length(geburtsjahr)>1){
!is.na(geburtsjahr)
}else{
T
}
)%>%
ungroup()
# test whether we have names in our data.set which match two people
Nachnamen <- namunique$NAME%>%
str_split(pattern = "\\s|[:punct:]", simplify = T)
Vornamen <- namunique$vorname%>%
str_split(pattern = "\\s|[:punct:]", simplify = T)
# get length of names
nachnamencount <- Nachnamen%>%
apply(MARGIN = 2, FUN = str_length)
# delete all names which consist only of one letter or are titles e.g. "von"
Nachnamen[nachnamencount<2|Nachnamen=="de"|Nachnamen=="De"|Nachnamen=="von"|Nachnamen=="Von"|Nachnamen=="la"|Nachnamen=="La"|Nachnamen=="der"|Nachnamen=="Der"|Nachnamen=="Van"|Nachnamen=="van"|Nachnamen=="di"|Nachnamen=="da"|Nachnamen=="Di"|Nachnamen=="Da"] <- ""
# set empty character fields to NA
Nachnamen[Nachnamen==""] <- NA
Vornamen[Vornamen==""] <- NA
# Paste all possible combinations to new columns in the data.frame
namunique$matches_1 <- paste(Vorname = Vornamen[ ,1], Nachnamen[, 1])
namunique$matches_2 <- str_c(Vornamen[ ,1], Nachnamen[, 2], sep = " ")
namunique$matches_3 <- str_c(Vornamen[ ,1], Nachnamen[, 3], sep = " ")
namunique$matches_4 <- str_c(Vornamen[ ,1], Nachnamen[, 4], sep = " ")
# create large vector with all matched names
AllUniqueNames <- c(namunique$matches_1, namunique$matches_2, namunique$matches_3, namunique$matches_4)%>%
na.omit()
# create frequency table with all names, select only those which occurr more than once
TableAllUniqueNames <- as.matrix(table(AllUniqueNames))
multipleNames <- data.frame("Name" = rownames(TableAllUniqueNames)[which(TableAllUniqueNames>1)],
"Frequenz" = TableAllUniqueNames[which(TableAllUniqueNames>1)])
# filter the data.frame for multiple matches
test <- filter(namunique, matches_1%in%multipleNames$Name|matches_2%in%multipleNames$Name|matches_3%in%multipleNames$Name|matches_4%in%multipleNames$Name)
#write_csv(test, "~/capstone_share/mehrfachmatches_neu.csv")
# dealing with critical matches:
# 1. identify which still match more than once
# 2. Add party regex to all matching more than once
# 3. recombine with entries which became singe matches
# 4. anti-join all multiple matches from original dict
# 5. rbind the new entries below
# 1. identify which still match more than once
df_mehrfach_nennungen_bearb <- read_csv2("capstone_share/mehrfach_nennungen_bearb.csv",
trim_ws = TRUE)
# create large vector with all matched names
vec_mehrfach <- c(df_mehrfach_nennungen_bearb$matches_1,
df_mehrfach_nennungen_bearb$matches_2,
df_mehrfach_nennungen_bearb$matches_3,
df_mehrfach_nennungen_bearb$matches_4)%>%
na.omit()
# create frequency table with all names, select only those which occurr more than once
mat_mehrfach <- as.matrix(table(vec_mehrfach))
df_mehrfach <- data.frame("Name" = rownames(mat_mehrfach)[which(mat_mehrfach>1)],
"Frequenz" = mat_mehrfach[which(mat_mehrfach>1)])
# filter the data.frame for multiple matches
df_immernoch_mehrfach <- filter(df_mehrfach_nennungen_bearb,
matches_1%in%df_mehrfach$Name|matches_2%in%df_mehrfach$Name|matches_3%in%df_mehrfach$Name|matches_4%in%df_mehrfach$Name)
# get only the resolved cases by anti-joining
df_mehrfach_nennungen_bearb <- anti_join(df_mehrfach_nennungen_bearb, df_immernoch_mehrfach)
# export the data.frame
# write_csv(df_immernoch_mehrfach, "capstone_share/immernoch_mehrfach.csv")
# checked by hand for conflicts. re-import
df_immernoch_mehrfach_bearbeitet <- read_csv("capstone_share/Data_Names/Mehrfachnennungen/immernoch_mehrfach_bearbeitet_6.csv")%>%
mutate(Loeschen = replace_na(Loeschen, 0),
Keine_Partyregex = replace_na(Keine_Partyregex, 0))%>% # replace na with 0 for relevant variables
filter(Loeschen != 1) # delete the ones which can be deleted (e.g. people that were included with more than one party even though their party change occured before our time period)
# add other names which were contained in the original dictionary more than once
df_mehrfach_nennungen_bearb <- bind_rows(df_immernoch_mehrfach_bearbeitet, df_mehrfach_nennungen_bearb)%>%
mutate(Keine_Partyregex = replace_na(Keine_Partyregex, 1),
Voller_Nachname = replace_na(Voller_Nachname, 0),
Voller_Vorname = replace_na(Voller_Vorname, 0),
Nicht_Zeitraum = replace_na(Nicht_Zeitraum, 0))
# make new regex
# preparing the regex: taking only the first first name
vornamen <- df_mehrfach_nennungen_bearb$vorname%>%
str_replace_all(pattern = "/", replacement = "|")%>%
str_split(pattern = "\\s", simplify = T)
# splitting the last name up
nachnamen1 <-df_mehrfach_nennungen_bearb$NAME%>%
str_split(pattern = "\\s|[:punct:]", simplify = T)
# get length of names
nachnamencount <- nachnamen1%>%
apply(MARGIN = 2, FUN = str_length)
# delete all names which consist only of one letter or are titles e.g. "von"
nachnamen1[nachnamencount<2|nachnamen1=="de"|nachnamen1=="De"|nachnamen1=="von"|nachnamen1=="Von"|nachnamen1=="la"|nachnamen1=="La"|nachnamen1=="der"|nachnamen1=="Der"|nachnamen1=="Van"|nachnamen1=="van"|nachnamen1=="di"|nachnamen1=="da"|nachnamen1=="Di"|nachnamen1=="Da"] <- ""
# create regex, which lists every part of a name as part separated by |
nachnamen1 <- nachnamen1%>%
apply(1, FUN = paste0, collapse = "|")%>%
str_replace_all(pattern = "\\|{2,}", replacement = "|")%>%
str_remove_all(pattern = "\\|{2,4}|(^\\|)|(\\|$)")
# create regex, which takes the whole last name, parts separated by .
nachnamen2 <-df_mehrfach_nennungen_bearb$NAME%>%
str_split(pattern = "\\s|[:punct:]")%>%
sapply(FUN = paste0, collapse = ".")%>%
str_replace_all(pattern = "(\\|){2}", replacement = "|")%>%
str_remove_all(pattern = "\\.{2,4}|(^\\|)|(\\|$)")
# paste the two regexes behind each other in the case that they differ
nachnamen <- ifelse(df_mehrfach_nennungen_bearb$Voller_Nachname==1,
nachnamen2,
ifelse(nachnamen1==nachnamen2,
nachnamen1,
paste0(nachnamen1, "|", nachnamen2)
)
)
# handling first names
vec_vornamen_ganz <-df_mehrfach_nennungen_bearb$vorname%>%
str_split(pattern = "\\s|[:punct:]")%>%
sapply(FUN = paste0, collapse = ".")%>%
str_remove_all(pattern = "\\.{2,4}|(^\\|)|(\\|$)")
vec_vornamen <- ifelse(df_mehrfach_nennungen_bearb$Voller_Vorname==1,
vec_vornamen_ganz,
vornamen[ ,1]
)
# create the final search regex
df_mehrfach_nennungen_bearb$Regex_Bruno <- paste0("(",
vec_vornamen,
")",
".{0,15}?",
"[^_\\-]",
"(",
nachnamen,
")(s)?(?![[:alpha:]_\\-])"
)
# add party information
# split data.frame
df_nicht_mehr_mehrfach <- df_mehrfach_nennungen_bearb%>%
filter(Keine_Partyregex==1) # sort those out, that do not need an addition of a party regex
df_mehrfach_nennungen_bearb <- df_mehrfach_nennungen_bearb%>%
filter(Keine_Partyregex==0) # those that need an addition of a party regex
# just an example to estimate length for lookaround
c("-Aussenpolitikerin", "-Nationalrätin",
"-Ständerätin", "-Umweltpolitikerin",
"-Mandatsträgerin", "-Shooting Star",
"-Fraktionspräsidentin", "-gesundheitspolitikerin")%>%
str_length()%>%max()+1
# 2. Add party regex to all matching more than once
# get party names
parteien <- df_mehrfach_nennungen_bearb$parteiname
# look at parties
parteien %>% table()
#deal with names which are often not only used as acronyms
parteien[parteien == "GPS"] <- "Grüne|GPS"
parteien[parteien == "GLP"] <- "Grünliberale|GLP"
parteien <- parteien%>%
str_replace_all("/", "\\|")%>%
str_replace_all("\\!", "\\.")
# make regex for parties
partyregex <- paste("(([:punct:]|\\s)(",
parteien,
"|",
str_to_lower(parteien),
"|",
str_to_upper(parteien),
")([:punct:]|\\s))")%>%
str_remove_all("\\s")
# create new regex to get the ambigous entries sorted out
Regex_Bruno_v2 <- paste0("(?<=(",partyregex,".{0,25}))",
df_mehrfach_nennungen_bearb$Regex_Bruno,
"|",
str_extract(df_mehrfach_nennungen_bearb$Regex_Bruno, ".*(?=\\(\\?\\!)"),
"(?=(.{0,25}",
partyregex,
"))(?![:alpha:])")
# create new name keys
Names_Dict_2 <- paste(df_mehrfach_nennungen_bearb$dict, df_mehrfach_nennungen_bearb$parteiname, sep = "_")
# set values in data.frame
df_mehrfach_nennungen_bearb$dict <- Names_Dict_2
df_mehrfach_nennungen_bearb$Regex_Bruno <- Regex_Bruno_v2
# 3. recombine with entries which became singe matches
df_mehrfach_handled<- rbind(df_nicht_mehr_mehrfach, df_mehrfach_nennungen_bearb)
# 4. anti-join all multiple matches from original dict
df_einfach <- anti_join(namunique, test)
# 5. rbind the new entries below
df_all_names <- bind_rows(df_einfach,
df_mehrfach_handled)
#ensure, that each entry only exists once
df_all_names <- df_all_names %>%
unique()
# add signifier to dictionary
df_all_names <- df_all_names%>%
mutate(dict = str_c("Personenmarker", dict, sep = "_"))
# change the name of niklaus-samuel gugger to find also nik gugger
df_all_names$Regex_Bruno[df_all_names$dict == "Personenmarker_Niklaus_Samuel_Gugger"] <- str_replace(string = df_all_names$Regex_Bruno[df_all_names$dict == "Personenmarker_Niklaus_Samuel_Gugger"],
pattern = "\\(Niklaus.Samuel\\)",
replacement = "(Niklaus.Samuel|Nik)")
# test the regex again
df_test_regexes <- df_all_names %>%
filter(dict%in%c("Personenmarker_Ueli_Maurer",
"Personenmarker_Karin_Keller_Sutter",
"Personenmarker_Susanne_Oberholzer",
"Personenmarker_Susanne_Leutenegger_Oberholzer",
"Personenmarker_Niklaus_Samuel_Gugger"))%>%
arrange(desc(dict))
vec_regexes <- df_test_regexes$dict
names(vec_regexes) <- df_test_regexes$Regex_Bruno
vec_regexes
vec_testsring <- c(vec_testsring, "Der EVP-Nationalrat und Restaurantbesitzer Niklaus-Samuel Gugger wird in den Zeitungen meist Nik Gugger genannt")
str_replace_all(string = vec_testsring, vec_regexes)
df_test_regexes <- df_all_names %>%
filter(dict%in%c("Personenmarker_Ueli_Maurer",
"Personenmarker_Karin_Keller_Sutter",
"Personenmarker_Susanne_Oberholzer",
"Personenmarker_Susanne_Leutenegger_Oberholzer",
"Personenmarker_Niklaus_Samuel_Gugger"))%>%
arrange(dict)
vec_regexes <- df_test_regexes$dict
names(vec_regexes) <- df_test_regexes$Regex_Bruno
vec_regexes
str_replace_all(string = vec_testsring, vec_regexes)
# the order in which the names are supplied seems to make the difference
# hence, it is necessary to sort by full lastnames and full firstnames
df_all_names <- df_all_names%>%
mutate(Voller_Vorname = replace_na(Voller_Vorname, 0), Voller_Nachname = replace_na(Voller_Nachname, 0))%>%
arrange(desc(Voller_Nachname), desc(Voller_Vorname))
# another option would be to restrict the number of free characters to the maximum of length complete first name - length first name used
saveRDS(df_all_names, "~/capstone_share/Names_Full_and_Lastnames/names_dict.rds")
##### correcting the dictionary parties ####
#### Preparations ####
# Cleaning
rm(list=ls())
# define stringsAsFactors = FALSE as default
options(stringsAsFactors = FALSE)
# Loading Packages
library(tidyverse)
#### Loading Data ####
# names Dictionary
df_names_dict <- readRDS("~/capstone_share/Names_Full_and_Lastnames/names_dict.rds")
#### Get misleading party codes
# create vector with unidentifiable parties
uncparty <- c("Übrige/Autres", "43", "41", "42", "44", "42", "-")
# remove whitespaces from partynames
df_names_dict$parteiname <- str_squish(df_names_dict$parteiname)
# get all dubious parties
findparty <- df_names_dict%>%
subset(parteiname %in% uncparty)
#### get correct party names (with some help from mighty google)
df_names_dict$parteiname[df_names_dict$name == "Florian Alter"] <- "AdG"
df_names_dict$parteiname[df_names_dict$name == "Olivier Battaglia"] <- "LDP"
df_names_dict$parteiname[df_names_dict$name == "Barbara Dahinden.Zahner"] <- "CSP"
df_names_dict$parteiname[df_names_dict$name == "Jean.Henri Dumont"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Anna Eugster"] <- "CVP"
df_names_dict$parteiname[df_names_dict$name == "Regula Gerig.Bucher"] <- "CSP"
df_names_dict$parteiname[df_names_dict$name == "Robert Gisler"] <- "FDP"
df_names_dict$parteiname[df_names_dict$name == "Stefan Gisler Schäfer"] <- "Al"
df_names_dict$parteiname[df_names_dict$name == "Madeline Heiniger"] <- "AdG"
df_names_dict$parteiname[df_names_dict$name == "Helmut Hersberger"] <- "FDP"
df_names_dict$parteiname[df_names_dict$name == "Helen Keiser.Fürrer"] <- "CSP"
df_names_dict$parteiname[df_names_dict$name == "Axel Marion"] <- "CVP"
df_names_dict$parteiname[df_names_dict$name == "Toni Moser.Stadelmann"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Christian Schäli"] <- "CSP"
df_names_dict$parteiname[df_names_dict$name == "Elisabeth Schnyder"] <- "SVP"
df_names_dict$parteiname[df_names_dict$name == "Vroni Straub.Müller"] <- "CSP"
df_names_dict$parteiname[df_names_dict$name == "Jaap van Dam"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Joe Vogler"] <- "CSP"
df_names_dict$parteiname[df_names_dict$name == "Stéphanie Vuichard"] <- "GPS"
df_names_dict$parteiname[df_names_dict$name == "Silvia Zbinden"] <- "CSP"
df_names_dict$parteiname[df_names_dict$name == "Tabea Zimmermann Gibson"] <- "GPS"
df_names_dict$parteiname[df_names_dict$name == "Sylvie Bonvin.Sansonnens"] <- "GPS"
df_names_dict$parteiname[df_names_dict$name == "Nicolas Pasquier"] <- "GPS"
df_names_dict$parteiname[df_names_dict$name == "Romain Schaer"] <- "SVP"
df_names_dict$parteiname[df_names_dict$name == "Guido Etterlin"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Robert Gisler"] <- "FDP"
df_names_dict$parteiname[df_names_dict$name == "Birgitta Michel Thenen"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Jonathan Prelicz"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Elsbeth Anderegg Marty"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Bettina Eschmann"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Erika Weber"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Antoine Chaix"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Prisca Bünter"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Luka Markic´"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Guy Tomaschett"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Eros Nicola Mellini"] <- "SVP"
df_names_dict$parteiname[df_names_dict$name == "Orlando Del Don"] <- "SVP"
df_names_dict$parteiname[df_names_dict$name == "Paolo Pamini"] <- "SVP"
df_names_dict$parteiname[df_names_dict$name == "Annalise Russi"] <- "GPS"
df_names_dict$parteiname[df_names_dict$name == "Alf Arnold Rosenkranz"] <- "GPS"
df_names_dict$parteiname[df_names_dict$name == "Beatrice Bünter"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Pia Tresch"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Armin Braunwalder Epp"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Christoph Schillig"] <- "GPS"
df_names_dict$parteiname[df_names_dict$name == "Alex Inderkum"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Nina Marty"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Adriano Prandi"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Nora Sommer"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Christiane Jaquet.Berger"] <- "PdA"
df_names_dict$parteiname[df_names_dict$name == "Gérald Cretegny"] <- "CVP"
df_names_dict$parteiname[df_names_dict$name == "Marcelle Monnet Terrettaz"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Camille Carron"] <- "GPS"
df_names_dict$parteiname[df_names_dict$name == "Sonia Z.Graggen.Salamin"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Francine Zufferey Molina"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Anne.Christine Bagnoud.Essellier"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Olivier Salamin"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Werner Jordan"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Blaise Carron"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Margaux Dubuis"] <- "SP"
df_names_dict$parteiname[df_names_dict$name == "Jolanda Spiess.Hegglin"] <- "GPS"
saveRDS(df_names_dict, "~/capstone_share/Names_Full_and_Lastnames/names_dict_corrected.rds")
##### applying the compounder ####
# load Data
df_filtered <- readRDS("~/capstone_share/df_texts_complete_all.rds")
df_all_names <- readRDS("~/capstone_share/Names_Full_and_Lastnames/names_dict_corrected.rds")
# create "manual" dictionary
# as named character vector
New_try_Bruno <- str_c(" ", df_all_names$dict, " ") #add whitespace to make sure that the token will be recognized later on as single token
names(New_try_Bruno) <- df_all_names$Regex_Bruno
#### Apply in parallel ####
cores <- detectCores()-4 # number of cores - cores not to use
articles <- nrow(df_filtered) # number of articles
result <- rep(NA, articles)
texts <- df_filtered$text
max <- length(texts)/cores
x <- seq_along(texts)
textsprepared <- split(texts, ceiling(x/max))
# define a core cluster
cl <- makeCluster(cores)
# register the core cluster for use with foreach
registerDoParallel(cl)
# exporting necessary functions
clusterExport(cl, c("%>%"))
tic("Bruno_Parallel")
result <- foreach(k = 1:length(textsprepared), .combine = 'c', .packages=c("stringr"))%dopar% {
str_replace_all(string = textsprepared[[k]], New_try_Bruno)
}
stopCluster(cl)
#
toc()
df_filtered$text <- result
saveRDS(df_filtered, "~/capstone_share/Names_Full_and_Lastnames/df_texts_fullnames.rds")
#### Transforming to quanteda corpus ####
library(quanteda)
quanteda_options(threads = 20)
quanteda_options("threads")
corp_filtered <- df_filtered %>%
corpus()
saveRDS(corp_filtered, "~/capstone_share/Names_Full_and_Lastnames/corp_texts_fullnames.rds")
toks_filtered <- corp_filtered%>%
tokens()
saveRDS(toks_filtered, "~/capstone_share/Names_Full_and_Lastnames/toks_texts_fullnames.rds")
#### Last Names to Keys ####
#### Preparations ####
# Cleaning
rm(list=ls())
# define stringsAsFactors = FALSE as default
options(stringsAsFactors = FALSE)
# Loading Packages
library(tidyverse)
library(tictoc)
library(foreach)
library(doParallel)
library(quanteda)
quanteda_options(threads = 20)
#### Loading Data ####
# Names
NamesDict <- readRDS("~/capstone_share/Names_Full_and_Lastnames/names_dict_corrected.rds")
# Texts
df_textsCompounded <- readRDS("~/capstone_share/Names_Full_and_Lastnames/df_texts_fullnames.rds")
# tokens
toks_comp <- readRDS("~/capstone_share/Names_Full_and_Lastnames/toks_texts_fullnames.rds")
#### know which texts contain which names ####
# constructing a gendered dictionary
dict <- dictionary(list(maennlich = NamesDict$dict[NamesDict$geschlecht == 2], weiblich = NamesDict$dict[NamesDict$geschlecht == 1]), tolower = F)
# constructing a dfm with counts of male / female names
geschlecht_dfm <- dfm(toks_comp, dictionary = dict, verbose = TRUE, tolower = F)
# subsetting the documents based on the occurence of names (at least one name is required)
toks_comp_reduced <- toks_comp %>%
tokens_subset(rowSums(geschlecht_dfm)>0)
# constructing a dfm of names and documents in which they occurr
name_dfm <- dfm(toks_comp_reduced, select = dict, verbose = TRUE, tolower = F)
# check whether there are Personenmarker which are not in the dictionary
test_dfm <- dfm(toks_comp_reduced, select = "Personenmarker_*", verbose = TRUE, tolower = F)
!names(test_dfm)%in%names(name_dfm)
# saveRDS(name_dfm, "~/capstone_share/Names_Full_and_Lastnames/dfmat_names_prov.rds")
# name_dfm <- readRDS("~/capstone_share/Names_Full_and_Lastnames/dfmat_names_prov.rds")
# converting this dfm to a tidy data.frame
df_tidy_names <- tidytext::tidy(name_dfm)
# taking the occurring names as a filter for the names
NamesUsed <- filter(NamesDict,
dict%in%unique(df_tidy_names$term))
#### preparing the search and replacement operation ####
# preparing the regex: splitting the last name up
nachnamen1 <-NamesUsed$NAME%>%
str_split(pattern = "\\s|[:punct:]", simplify = T)
# get length of names
nachnamencount <- nachnamen1%>%
apply(MARGIN = 2, FUN = str_length)
# delete all names which consist only of one letter or are titles e.g. "von"
nachnamen1[nachnamencount<2|nachnamen1=="de"|nachnamen1=="De"|nachnamen1=="von"|nachnamen1=="Von"|nachnamen1=="la"|nachnamen1=="La"|nachnamen1=="der"|nachnamen1=="Der"|nachnamen1=="Van"|nachnamen1=="van"|nachnamen1=="di"|nachnamen1=="da"|nachnamen1=="Di"|nachnamen1=="Da"] <- ""
# create regex, which lists every part of a name as part separated by |
nachnamen1 <- nachnamen1%>%
apply(1, FUN = paste0, collapse = "|")%>%
str_replace_all(pattern = "\\|{2,}", replacement = "|")%>%
str_remove_all(pattern = "\\|{2,4}|(^\\|)|(\\|$)")
# create regex, which takes the whole last name, parts separated by .
nachnamen2 <-NamesUsed$NAME%>%
str_split(pattern = "\\s|[:punct:]")%>%
sapply(FUN = paste0, collapse = ".")%>%
str_replace_all(pattern = "(\\|){2}", replacement = "|")%>%
str_remove_all(pattern = "\\.{2,4}|(^\\|)|(\\|$)")
# paste the two regexes behind each other in the case that they differ
nachnamen <- ifelse(nachnamen1==nachnamen2, nachnamen1,
paste0(nachnamen1, "|", nachnamen2))
# create the final search regex
NamesUsed$Regex_Lastnames <- paste0("(?<=\\s)(",
nachnamen,
")(s)?(?![[:alpha:]_\\-])"
)
# # replace 0 with NA
# df_dfmat_names[df_dfmat_names == 0] <- NA
#
# # convert data from wide to long
# df_names_documents <- gather(df_dfmat_names,
# key = "dict",
# value = "count",
# na.rm = T,
# -document)
df_tidy_names <- rename(df_tidy_names, "dict" = "term")
# merge data
df_Names_Documents <- merge(df_tidy_names,
NamesUsed,
by = "dict",
all.y =T)
# filter texts by doc.ids
df_texts_politicians <- filter(df_textsCompounded,doc_id%in%unique(df_tidy_names$document))
# set.seed(1234)
# df_texts_politicians_samp <- sample_n(df_texts_politicians, 10000)
# df_texts_politicians_samp_s <- df_texts_politicians_samp
# df_texts_politicians_samp_p <- df_texts_politicians_samp
#
# tic("sequential")
# #### replacing the names ####
# # replace last names by keys
# for(i in 1:nrow(df_texts_politicians_samp_s)){
# doc_id_i <- df_texts_politicians_samp_s$doc_id[i] # get doc.id
#
# iterdata <- filter(df_Names_Documents, document == doc_id_i)%>% # filter for doc_id
# select(dict, Regex_Lastnames) # select only relevant columns
#
# pattern_replacement <- iterdata$dict # create character vector
#
# names(pattern_replacement) <- iterdata$Regex_Lastnames # name the character vector
#
# df_texts_politicians_samp_s$text[i] <- df_texts_politicians_samp_s$text[i] %>%
# str_replace_all(pattern_replacement)
#
# #cat(i, "of", nrow(df_texts_politicians_samp), "articles edited \n")
# }
# toc()
# do the same stuff in parallel
tic("parallel")
#### Apply in parallel ####
quanteda_options(threads = 2)
# prepare by creating a list of named character vectors
names_docs <- str_c(" ", df_Names_Documents$dict, " ")
names(names_docs) <- df_Names_Documents$Regex_Lastnames
ls_names_vectors <- split(names_docs, df_Names_Documents$document)
cores <- detectCores()-4 # number of cores - cores not to use
articles <- nrow(df_texts_politicians) # number of articles
result <- rep(NA, articles)
# define a core cluster
cl <- makeCluster(cores)
# register the core cluster for use with foreach
registerDoParallel(cl)
# exporting necessary functions
clusterExport(cl, c("%>%"))
result <- foreach(i = 1:nrow(df_texts_politicians), .combine = 'c', .packages=c("stringr"))%dopar% {
df_texts_politicians$text[i] %>%
str_replace_all(ls_names_vectors[[which(df_texts_politicians$doc_id[i]==names(ls_names_vectors))]])
}
stopCluster(cl)
#
df_texts_politicians$text <- result
toc()
#### saving the output ####
saveRDS(df_texts_politicians, "~/capstone_share/Names_Full_and_Lastnames/df_texts_full_and_lastnames.rds")
saveRDS(df_dfmat_names, "~/capstone_share/Names_Full_and_Lastnames/df_dfmat_fullnames.rds")
saveRDS(geschlecht_dfm, "~/capstone_share/Names_Full_and_Lastnames/dfmat_sex_fullnames.rds")
##### converting to corpus and tokenizing ####
# Cleaning
rm(list=ls())
# define stringsAsFactors = FALSE as default
options(stringsAsFactors = FALSE)
# Loading Packages
library(tidyverse)
library(tictoc)
library(quanteda)
#### Loading Data ####
df_texts_full_and_lastnames <- readRDS("~/capstone_share/Names_Full_and_Lastnames/df_texts_full_and_lastnames.rds")
#### creating corpus and tokenizing ####
# maximize performance
quanteda_options(threads = 18)
quanteda_options("threads")
# creating corpus
corp_final <- df_texts_full_and_lastnames %>%
corpus()
# saving
saveRDS(corp_final, "~/capstone_share/Names_Full_and_Lastnames/corp_texts_full_and_lastnames.rds")
# tokenizing
toks_final <- corp_final%>%
tokens()
# saving
saveRDS(toks_final, "~/capstone_share/Names_Full_and_Lastnames/toks_texts_full_and_lastnames.rds")
###### Creating information on which politician (from which party) is in which text #####
# Cleaning
rm(list=ls())
# define stringsAsFactors = FALSE as default
options(stringsAsFactors = FALSE)
# Loading Packages
library(tidyverse)
library(tictoc)
library(quanteda)
quanteda_options(threads = 12)
#### Loading Data ####
# Names
NamesDict <- readRDS("~/capstone_share/Names_Full_and_Lastnames/names_dict_corrected.rds")
# tokens
toks_full <- readRDS("~/capstone_share/Names_Full_and_Lastnames/toks_texts_full_and_lastnames.rds")
#### know which texts contain which names ####
# constructing a gendered dictionary
dict <- dictionary(list(maennlich = NamesDict$dict[NamesDict$geschlecht == 2], weiblich = NamesDict$dict[NamesDict$geschlecht == 1]), tolower = F)
# constructing a dfm with counts of male / female names
geschlecht_dfm <- dfm(toks_full, dictionary = dict, verbose = TRUE, tolower = F)
# constructing a dfm of names and documents in which they occurr
name_dfm <- dfm(toks_full, select = dict, verbose = TRUE, tolower = F)
# converting this dfm to a tidy data.frame
df_tidy_names <- tidytext::tidy(name_dfm)
# taking the occurring names as a filter for the names
NamesUsed <- filter(NamesDict,dict%in%unique(df_tidy_names$term))
# rename variables to fit
df_tidy_names <- rename(df_tidy_names, "dict" = "term")
# merge data
df_Names_Documents <- merge(df_tidy_names,
NamesUsed,
by = "dict",
all.y =T)
#### saving the output ####
saveRDS(df_Names_Documents, "~/capstone_share/Names_Full_and_Lastnames/df_names_parties_etc_per_doc.rds")
saveRDS(name_dfm, "~/capstone_share/Names_Full_and_Lastnames/dfmat_full_and_lastnames.rds")
saveRDS(geschlecht_dfm, "~/capstone_share/Names_Full_and_Lastnames/dfmat_sex_full_and_lastnames.rds")
#### Compunding names in legends ####
#### Preparations ####
# Cleaning
rm(list=ls())
# define stringsAsFactors = FALSE as default
options(stringsAsFactors = FALSE)
# Loading Packages
library(tidyverse)
library(readtext)
library(readxl)
library(doParallel)
library(foreach)
library(tictoc)
##### applying the compounder ####
# load Data
df_all_names <- readRDS("~/capstone_share/Names_Full_and_Lastnames/names_dict_corrected.rds")
df_full_and_lastnames <- readRDS("~/capstone_share/Names_Full_and_Lastnames/df_texts_full_and_lastnames.rds")
# create "manual" dictionary
# as named character vector
New_try_Bruno <- str_c(" ", df_all_names$dict, " ") #add whitespace to make sure that the token will be recognized later on as single token
names(New_try_Bruno) <- df_all_names$Regex_Bruno
#### Apply in parallel ####
cores <- detectCores()-4 # number of cores - cores not to use
articles <- nrow(df_full_and_lastnames) # number of articles
result <- rep(NA, articles)
texts <- replace_na(df_full_and_lastnames$lg, " ")
max <- length(texts)/cores
x <- seq_along(texts)
textsprepared <- split(texts, ceiling(x/max))
# define a core cluster
cl <- makeCluster(cores)
# register the core cluster for use with foreach
registerDoParallel(cl)
# exporting necessary functions
clusterExport(cl, c("%>%"))
tic("Bruno_Parallel")
result <- foreach(k = 1:length(textsprepared), .combine = 'c', .packages=c("stringr"))%dopar% {
str_replace_all(string = textsprepared[[k]], New_try_Bruno)
}
stopCluster(cl)
#
toc()
df_full_and_lastnames$lg <- result
saveRDS(df_full_and_lastnames, "~/capstone_share/Names_Full_and_Lastnames/df_legends_fullnames.rds")
#### Transforming to quanteda corpus ####
library(quanteda)
quanteda_options(threads = 20)
quanteda_options("threads")
corp_filtered <- df_full_and_lastnames %>%
corpus(text_field = "lg")
saveRDS(corp_filtered, "~/capstone_share/Names_Full_and_Lastnames/corp_legends_fullnames.rds")
toks_filtered <- corp_filtered%>%
tokens()
saveRDS(toks_filtered, "~/capstone_share/Names_Full_and_Lastnames/toks_legends_fullnames.rds")
#### Adding Control Variables ####
#### Preparations ####
# Cleaning
rm(list=ls())
# define stringsAsFactors = FALSE as default
options(stringsAsFactors = FALSE)
# Loading Packages
library(tidyverse)
library(tictoc)
library(readxl)
library(quanteda)
#quanteda_options(threads = 6)
#### Loading Data ####
# Names Dictionary
df_names_dict <- readRDS("~/capstone_share/Names_Full_and_Lastnames/names_dict_corrected.rds")
# Controls
df_sonderrollen <- read_csv("capstone_share/Data_Names/Kontrols/Kontrols_ Sonderrollen.csv")
# Parliament Data
df_parldata <- read_excel("~/capstone_share/Data_Names/Parlamentsdienste/Ratsmitglieder_1848_DE.xlsx")
#df_names_parties_doc <- readRDS("~/capstone_share/Names_Full_and_Lastnames/df_names_parties_etc_per_doc.rds")
#### Making data more usefull ####