-
Notifications
You must be signed in to change notification settings - Fork 1
/
combined_submitted_code.py
2283 lines (1497 loc) · 82.9 KB
/
combined_submitted_code.py
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
import pandas as pd
from bs4 import BeautifulSoup
import re
import requests
import string
from SPARQLWrapper import SPARQLWrapper, JSON
pd.options.mode.chained_assignment = None
import numpy as np
from country_list import countries_for_language
import wikipedia
import math
import time
from urllib.error import HTTPError
from wikipedia import PageError, DisambiguationError
from collections import OrderedDict
import matplotlib.pyplot as plt
import spacy
import random
from spacy.util import minibatch, compounding
from pathlib import Path
import nltk
from nltk.sem import extract_rels,rtuple
from nltk.chunk import tree2conlltags
from spacy.symbols import prep, VERB, pobj, PROPN, ADP
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
import pandas as pd
from scipy import interpolate
import os
import os.path
import ssl
import stat
import subprocess
import sys
import pytesseract
import cv2
import warnings
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
warnings.simplefilter(action='ignore', category=pd.errors.PerformanceWarning)
import pandas as pd
import pandas as pd
pd.options.mode.chained_assignment = None
import copy
ssl._create_default_https_context = ssl._create_unverified_context
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
warnings.simplefilter(action='ignore', category=pd.errors.PerformanceWarning)
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import RobustScaler
from sklearn.preprocessing import Normalizer
from sklearn.preprocessing import QuantileTransformer
from sklearn.preprocessing import PowerTransformer
import geopandas as gpd
from sklearn.decomposition import PCA
from sklearn.preprocessing import MinMaxScaler
pd.options.mode.chained_assignment = None
import prince
#General Wrapper functionsto prevent the actual function throwing an error
def math_wrapper_is_nan(x):
"""
Function that checks where x is nan without throwing an error
"""
try:
return math.isnan(x)
except TypeError:
return False
def soup_find_wrapper(x):
"""
Function that checks if span in Soup object without throwing an error if the Soup object is None
"""
try:
return x.find("span", itemprop="name").text
except AttributeError:
return np.nan
def extract_wikidata_identifier(wikidata_link):
"""
Function that returns the wikidata identifier from the URL or URI
"""
if math_wrapper_is_nan(wikidata_link) or wikidata_link == None:
return np.nan
identifier = wikidata_link.split('/')[-1]
return identifier
#Read in dataframes that are needed
index_of_places = pd.read_csv("IPN_GB_2021.csv", encoding = "ISO-8859-1")
countries = dict(countries_for_language('en'))
"""
To make the implementation clear, I have sectioned the code into the following sections
In each section I usually define any relevent functions and follow this with the code that calls these functions
It does take quite a while to finish
SECTION 1: DATA COLLECTION
Subtask 1 : Collect name and wikidata identifier on all MPs
Tasks:
1.
i) Extract unique identifiers, parlimentary number, and optionally place of birth from Wikidata of MPs from first UK parliament to current UK Parliament
2
i) Extract names and unique identifiers from Wikipedia of MPs from first UK parliament to current UK parliament
3
i) Join these two datasets together
Subtask 2 : Collect place of birth data
Tasks:
1.
i) Collect place of birth data from Wikipedia, Wikitree, Geni and Rush Parliamentary Archives
2.
i) Process and standarise this data
3.
i) Take the mode of this data to find historic county
Subtask 3 : Collection population data
Tasks:
1.
i) Extract British population data from Vision of Britian
ii) Combine this data into historical county
2.
i) Perform OCR and process Northern Ireland population data
SECTION 2: Graph and Map Creation
Subtask 1 : Create choropleth map
Subtask 2 : Create PCA
Subtask 3 : Create MFA
Subtask 4 : Create MCA
"""
##########################################################################
# SECTION 1 SUBTASK 1 TASK 1)i - Query Wikidata #
##########################################################################
#First SPARQL query that gathers all MPS from every parliament and optionally their date of birth, gender and place of birth
sparql = SPARQLWrapper("https://query.wikidata.org/sparql")
sparql.setQuery("""
SELECT ?person ?PN ?gender ?dateOfBirth ?personLabel ?PNLabel ?genderLabel ?dateOfBirthLabel ?placeOfBirth ?placeOfBirthLabel
WHERE
{
?person wdt:P39 ?PN .
?PN wdt:P279 wd:Q16707842 .
OPTIONAL {?person wdt:P21 ?gender . }
OPTIONAL {?person wdt:P569 ?dateOfBirth . }
OPTIONAL {?person wdt:P19 ?placeOfBirth . }
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
""")
sparql.setReturnFormat(JSON)
wikidata_query_result = sparql.query().convert()
first_wikidata_query = pd.json_normalize(wikidata_query_result['results']['bindings'])
def return_party_electory_startdate(column):
"""
Function that returns the electoral district, the political party and the start time for an MP for a specific parliament they served in
These queries had to be split up as they were exceeded the quota set out by the sparql python interface
"""
sparql = SPARQLWrapper("https://query.wikidata.org/sparql")
#Create final dataframe results will be appended to
columns = ['person.value', 'group.value', 'elect.value', 'PNN.value', 'starttime.value']
final_results = pd.DataFrame(columns = columns)
nrows = 100
start = 0
end = nrows
reached_end = False
#Submit MP wikidata identifier in batches of length nrows
for i in range(math.ceil((len(column) + 1)/nrows)):
#Avoid too many requests Error
time.sleep(3)
values = '{ '
for j in range(start,end):
#Check if the end of the column has been reached
if j >= len(df):
reached_end = True
break
wikidata_identifier = column[j]
#Append the wikidata identifiers to the values
values += ' wd:' + wikidata_identifier + ' '
values += " }"
done = False
while done == False:
try:
#Submit query with specific values
sparql.setQuery("""SELECT ?person ?PNN ?starttime ?elect ?group ?electLabel ?groupLabel WHERE {
VALUES ?person """ + values + """
?person p:P39 ?statement .
?statement ps:P39 ?PNN .
OPTIONAL{ ?statement pq:P580 ?starttime .}
OPTIONAL{ ?statement pq:P768 ?elect . }
OPTIONAL{ ?statement pq:P4100 ?group . }
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
} """)
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
results_df = pd.json_normalize(results['results']['bindings'])
done = True
except HTTPError:
#If too many requests error try again
pass
if 'group.value' not in list(results_df.columns):
results_df['group.value'] = np.nan
elif 'elect.value' not in list(results_df.columns):
results_df['elect.value'] = np.nan
try:
final_results = final_results.append(results_df[['person.value', 'group.value', 'elect.value', 'PNN.value', 'starttime.value']])
except KeyError:
pass
start += nrows
end += nrows
if reached_end == True:
break
final_results['person.value'] = final_results['person.value'].apply(extract_wikidata_identifier)
final_results.set_index(final_results['person.value'], inplace = True)
final_results = final_results.drop(columns=['person.value'])
return final_results
def retrive_parliament_number(string):
string = string.replace('Member of the ', '')
string = string.replace('Parliament of the United Kingdom', '')
string = string.replace('th ', '')
string = string.replace('nd', '')
string = string.replace('st', '')
string = string.replace('rd', '')
ParliamentNumber = int(string)
return ParliamentNumber
#Process the first wikidata query to extract the unique Wikidata identifier from the wikidata URI returned
first_wikidata_query['ID'] = first_wikidata_query['person.value'].apply(extract_wikidata_identifier)
first_wikidata_query['parliamentNumber'] = first_wikidata_query['PNLabel.value'].apply(retrive_parliament_number)
#Make a section wikidata query that returns parliamentary group , electoral district and start date for each parliament an MP served in
second_wikidata_query = return_party_electory_startdate(first_wikidata_query['ID'])
#Process the two query datasets so they can be joined
unique_PN = list(first_wikidata_query['PN.value'].unique())
second_wikidata_query = second_wikidata_query[second_wikidata_query['PNN.value'].isin(unique_PN)]
second_wikidata_query.drop_duplicates(inplace=True)
second_wikidata_query = second_wikidata_query.rename(columns={'PNN.value': 'PN.value'})
first_wikidata_query['person.value'] = first_wikidata_query['person.value'].apply(extract_wikidata_identifier)
#Perform left join
wikidataQuery = pd.merge(first_wikidata_query, second_wikidata_query, how='left', left_on=['person.value','PN.value'], right_on = ['person.value','PN.value'])
#Save dataframe
wikidataQuery.to_csv('wikidataQuery.csv') # combined_df
wikidataQuery = pd.read_csv('wikidataQuery.csv')
##########################################################################
# SECTION 1 SUBTASK 1 TASK 2)i - Extract Wikipedia Data #
##########################################################################
#Create relevant functions
def extract_names_for_letter(url, letter):
"""
Function that extracts the names and a link to the wikipedia page of all MPs that start with a specific letter and in a specific time period.
"""
page = requests.get(url)
time.sleep(3)
soup = BeautifulSoup(page.text, 'html.parser')
names, links = [], []
target = soup.find('h3',text = str(letter))
try:
for sib in target.find_next_siblings():
if sib.name=="h3":
break
else:
lines = sib.find_all('li')
for line in lines:
link = line.find('a', href = True)['href']
link = "https://en.wikipedia.org" + link
name = line.text
names.append(name)
links.append(link)
except AttributeError:
pass
return names, links
def construct_url(time_period, letter):
"""
Function that creates URL that links to the wikipedia page for that specific time period and letter
"""
if '-' in time_period:
time = time_period.split('-')
url = " https://en.wikipedia.org/w/index.php?title=Category:UK_MPs_"+ time[0] + "%E2%80%93" + time[1] + "&from=" + str(letter)
else:
url = "https://en.wikipedia.org/w/index.php?title=Category:UK_MPs_" + time_period + "&from=" + str(letter)
return url
def return_wikidata_identifier_from_wikipedia_page(url):
"""
Function that returns the wikidata identifier from a wikipedia page
"""
page = requests.get(url)
time.sleep(3)
soup = BeautifulSoup(page.text, 'html.parser')
try:
link = soup.find('a', {'accesskey':"g"})['href']
except TypeError:
return None
link = str(link).replace('Special:EntityPage/', '')
return link
letters = list(string.ascii_uppercase)
overall_names = []
overall_links = []
time_periods = ['1801-1802', '1802-1806', '1806-1807', '1807-1812', '1812-1818', '1818-1820', '1820-1826', '1826-1830', '1830-1831', '1831-1832', '1832-1835', '1835-1837', '1837-1841', '1841-1847', '1847-1852', '1852-1857', '1857-1859', '1859-1865', '1865-1868', '1868-1874', '1874-1880', '1880-1885', '1885-1886', '1886-1892', '1892-1895', '1895-1900', '1900-1906', '1906-1910', '1910-1918', '1918-1922', '1974', '1910', '2019–present']
## First extract links and names of MPs from all Parliments from 1st-58th:
for time_period in time_periods:
for letter in letters:
url = construct_url(time_period, letter)
names, links = extract_names_for_letter(url, letter)
overall_names.extend(names)
overall_links.extend(links)
#Add this to a dataframe
wikipedia_df = pd.DataFrame()
wikipedia_df['names'] = overall_names
wikipedia_df['links'] = overall_links
wikipedia_df.to_csv('wikipedia_names.csv')
wikipedia_df = pd.read_csv('wikipedia_names.csv')
wikipedia_df['person.value'] = wikipedia_df['links'].apply(return_wikidata_identifier_from_wikipedia_page)
wikipedia_df.to_csv('wikipediaQuery.csv')
##########################################################################################################
# SECTION 1 SUBTASK 1 TASK 3)i - Join Wikidata and Wikipedia datasets on unique wikidata identifier #
##########################################################################################################
#Read in data:
wikidata_query = pd.read_csv('wikidataQuery.csv')
wikipedia_query = pd.read_csv('wikipediaQuery.csv')
#Remove duplicate entries (where a person served in more than one Parliament) to save time on processing
wikidata_query = wikidata_query.drop_duplicates(subset = ['person.value'])
wikipedia_query = wikipedia_query.drop_duplicates(subset = ['person.value'])
#Create wikidata_identifier to join the two datasets on
wikipedia_query = wikipedia_query.rename(columns={'person.value': 'wikidata_link'})
wikipedia_query['wikidata_identifier'] = wikipedia_query['wikidata_link'].apply(extract_wikidata_identifier)
wikidata_query['wikidata_identifier'] = wikidata_query['person.value'].apply(extract_wikidata_identifier)
wikidata_query.set_index('wikidata_identifier', inplace=True)
wikipedia_query.set_index('wikidata_identifier', inplace=True)
#Join the datasets
combined_df = pd.concat([wikipedia_query, wikidata_query], axis=1)
combined_df['ID'] = combined_df.index
combined_df.to_csv('combined.csv')
#Drop any people that are included by both the wikipedia and wikidata queries
combined_df_unique = combined_df.drop_duplicates(subset = ['ID'])
#Yields a total of 12209 unique people
combined_df_unique.set_index(combined_df_unique['ID'], inplace = True)
combined_df_unique.to_csv('unique.csv')
###########################################################################################
# SECTION 1 SUBTASK 2 TASK 1)i - Collect place of birth from additional sources #
###########################################################################################
#Define relevant functions
def returning_attribute_from_wikidata_identifier(column, wdt, nrows):
"""
General function that finds the wdt relationship passed in with a column of wikidata identifiers
For example if wdt = 'P19' and the column was a column of wikidata identifiers for MPs
it would return a list of the places of birth of these MPs
"""
sparql = SPARQLWrapper("https://query.wikidata.org/sparql")
final_results = pd.DataFrame(columns = ['person.value', 'attribute.value'])
start = 0
end = nrows
total_considered = 0
for i in range(len(column)//nrows):
time.sleep(5)
values = '{ '
for i in range(start,end):
wikidata_identifier = column[i]
values += ' wd:' + wikidata_identifier + ' '
total_considered += 1
values += " }"
sparql.setQuery("""
SELECT ?person ?attribute {
VALUES ?person """ + values + """
?person wdt:""" + wdt +""" ?attribute.
}
""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
results_df = pd.json_normalize(results['results']['bindings'])
final_results = final_results.append(results_df[['person.value', 'attribute.value']])
start += 300
end += 300
final_results['person.value'] = final_results['person.value'].apply(extract_wikidata_identifier)
final_results.set_index(final_results['person.value'], inplace = True)
final_results = final_results.drop(columns=['person.value'])
return final_results
def pattern_match_wikipedia_place_of_birth(text):
"""
Function that uses pattern matchig to return the place of birth from a wikipedia infobox
given the text in the infobox
"""
location = None
if re.search('\d{4}[A-Z]{1}', text) is not None:
start, end = re.search('\d{4}[A-Z]{1}', text).span()
location = text[end-1:]
elif ')' in text:
location = text.split(')')[-1]
elif '[1]' in text:
if '[2]' in text:
location = text.split('[2]')[-1]
else:
location = text.split('[1]')[-1]
elif re.search('[a-z]{1}[A-Z]{1}', text) is not None:
start, end = re.search('[a-z]{1}[A-Z]{1}', text).span()
location = text[:end]
return location
def place_of_birth_from_table(url):
"""
Function that returns the place of birth (if listed in infobox on wikipedia page),
if there is no place of birth or no info box it return None
"""
if "https://en.wikipedia.org" not in url:
url = "https://en.wikipedia.org" + url
done = False
while done == False:
try:
page = requests.get(url)
done = True
except:
done = False
soup = BeautifulSoup(page.text, 'html.parser')
table = soup.find('table',{'class':'infobox vcard'})
place_of_birth = None
try:
for tr in table.find_all('tr'):
content = tr.text
if 'Born' in content:
#print(url)
content = content.replace('Born', '')
place_of_birth = pattern_match_wikipedia_place_of_birth(content)
if place_of_birth == None:
return place_of_birth
if bool(re.search(r'\d', place_of_birth)):
return None
return place_of_birth
except AttributeError:
return place_of_birth
def return_wikitree_place_of_birth(wikitree_identifier):
"""
Function that returns the place of birth of an MP (idenitifed by a unique Wikitree identifier)
if it is listed on the wikitree website
"""
if math_wrapper_is_nan(wikitree_identifier):
return np.nan
elif wikitree_identifier == None:
return np.nan
url = "https://www.wikitree.com/wiki/" + str(wikitree_identifier)
page = requests.get(url)
time.sleep(3)
soup = BeautifulSoup(page.text, 'html.parser')
subset_soup = soup.find("span", itemprop="birthPlace")
place = soup_find_wrapper(subset_soup)
return place
def return_geni_place_of_birth(geni_identifier):
"""
Function that returns the place of birth of an MP
(identified by a unique Geni idenitifer) if listed on the Geni website
"""
if math_wrapper_is_nan(geni_identifier):
return np.nan
elif geni_identifier == None:
return np.nan
url = "https://www.geni.com/search?search_type=people&names=" + str(int(geni_identifier))
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
subset_soup = soup.find("td", {"id": "birth_location"})
full_address = soup_find_wrapper(subset_soup)
return full_address
def return_rush_parliamentary_archive_place_of_birth(rush_parliamentary_identifier):
"""
Function that returns the place of birth of an MP
(identified by a unique Rush Parliamentary Idenitifer) if listed on the Rush Parliamentary website
"""
if math_wrapper_is_nan(rush_parliamentary_identifier):
return np.nan
elif rush_parliamentary_identifier == None:
return np.nan
url = "https://membersafter1832.historyofparliamentonline.org/members/" + str(int(rush_parliamentary_identifier))
page = requests.get(url)
time.sleep(3)
soup = BeautifulSoup(page.text, 'html.parser')
df = soup.find_all("dl", {'class': 'row'})
for ele in df:
for (dt, dd) in zip(ele.find_all("dt"), ele.find_all("dd")):
if 'Birth place' in dt.text:
return dd.text
return np.nan
def return_wikipedia_from_wikidata(wikidata_identifier):
"""
Function that returns a URL for the English wikipedia page associated
with the wikidata identifier passed in
"""
url = "https://www.wikidata.org/wiki/" + wikidata_identifier
page = requests.get(url, timeout = 5)
soup = BeautifulSoup(page.text, 'html')
sub_soup = soup.find_all('span', {'class':'wikibase-sitelinkview-page', 'lang':'en'})
for soup in sub_soup:
link = soup.find('a', href= True)['href']
if 'https://en.wikipedia.org/wiki/' in link:
return link
return np.nan
def extract_text_from_wikipedia(wikipedia_url):
"""
Function that extracts the text from a wikipedia article
"""
page = requests.get(wikipedia_url)
soup = BeautifulSoup(page.text, 'lxml')
text = ''
number_of_sentences = 0
for paragraph in soup.find_all('p'):
text += paragraph.text
text += ' '
if '.' in paragraph.text:
number_of_sentences += 1
if number_of_sentences > 4:
break
text = re.sub(r'\[.*?\]+', '', text)
text = text.replace('\n', '')
return text
nlp = spacy.load('en_core_web_sm')
def parsing_the_dependency_tree(sentence):
"""
Function that performs POS tagging by parsing the dependency tree of a sentance
"""
doc = nlp(sentence)
verbs = []
for possible_subject in doc:
if possible_subject.dep == prep and possible_subject.head.pos == VERB:
if str(possible_subject.head) == 'born':
verbs.append(possible_subject)
if verbs == []:
return verbs
for possible_subject in doc:
if possible_subject.dep == pobj and possible_subject.head.pos == ADP:
if possible_subject.head == verbs[0]:
verbs.append(possible_subject)
return verbs[-1]
def extract_place_of_birth_from_unstructured_text(wikipedia_url):
"""
Function that extracts the place of birth from unstructured text
"""
text = extract_text_from_wikipedia(wikipedia_url)
sentences = re.split('(?<=[\.\?\!])\s*', text)
born_synonyms = ['born', 'comes from', 'originates', 'originated']
final_sentences = []
for sentence in sentences:
for born_synonym in born_synonyms:
if born_synonym in sentence:
final_sentences.append(sentence)
for sentence in final_sentences:
place_of_birth = parsing_the_dependency_tree(sentence)
return place_of_birth
#Now call these functions by first extracting relevant identifiers
#Retrieve Parliamentary Rush Identifier, this is the entity that has the wikidata Rush Parliamentary Archive ID (P4471) relationship with the person
df = returning_attribute_from_wikidata_identifier(combined_df_unique['ID'], nrows = 300, wdt = "P4471")
combined_df_unique = combined_df_unique.join(df)
combined_df_unique = combined_df_unique.rename(columns={'attribute.value': 'rush'})
#Retrieve Wikitree Identifier, this is the entity that has the wikidata Wikitree ID (P2929) relationship with the person
df = returning_attribute_from_wikidata_identifier(combined_df_unique['ID'], nrows = 300, wdt = "P2949")
combined_df_unique = combined_df_unique.join(df)
combined_df_unique = combined_df_unique.rename(columns={'attribute.value': 'wikitree'})
#Retrieve Geni Identifier, this is the entity that has the wikidata Geni ID (P2600) relationship with the person
df = returning_attribute_from_wikidata_identifier(combined_df_unique['ID'], nrows = 300, wdt = "P2600")
combined_df_unique = combined_df_unique.join(df)
combined_df_unique = combined_df_unique.rename(columns={'attribute.value': 'geni'})
#Return place of birth from these websites:
#Place of birth from Parliamentary Rush Website. The page has been found using the Parliamentary Rush ID found previously
combined_df_unique['rush_place_of_birth'] = combined_df_unique['rush'].apply(return_rush_parliamentary_archive_place_of_birth)
#Place of birth from Wikitree Website. The page has been found using the Wikitree ID found previously
combined_df_unique['wikitree_place_of_birth'] = combined_df_unique['wikitree'].apply(return_wikitree_place_of_birth)
#Place of birth from Geni Website. The page has been found using the Geni ID found previously
combined_df_unique['geni_place_of_birth'] = combined_df_unique['geni'].apply(return_geni_place_of_birth)
#Get wikipedia link associated with the person from the wikidata page. This link will be the unique to the person
combined_df_unique['wikipedia'] = combined_df_unique.apply(lambda x: return_wikipedia_from_wikidata(x['ID']) if(pd.isnull(x['links'])) else np.nan, axis = 1)
combined_df_unique['wikipedia'].fillna(combined_df_unique['links'], inplace=True)
#If the wikipedia page contains an infobox, look for the place of birth there
combined_df_unique['wikipedia_place_of_birth'] = combined_df_unique.apply(lambda x: place_of_birth_from_table(x['wikipedia']) if(pd.notnull(x['wikipedia'])) else np.nan, axis = 1)
#Need to set wikidata_place_of_birth column
#birthPlace.value
if 'placeOfBirth.value' in list(combined_df_unique.columns):
combined_df_unique = combined_df_unique.rename(columns={'placeOfBirth.value': 'wikidata_place_of_birth'})
##########################################################################
# SECTION 1 SUBTASK 2 TASK 2)i - Process place of birth data #
##########################################################################
#Define relevant functions
def wikidata_search_irish_county(wikidata_identifier):
"""
Function that returns the Irish historical county that a place is in (if applicable)
(the county that has the wikidata relationship P7959 with the wikidata identifier passed in)
"""
query_string = """
SELECT ?county ?countyLabel
{ wd:""" + str(wikidata_identifier) + """ wdt:P7959 ?county .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
"""
done = False
while done == False:
try:
sparql = SPARQLWrapper("https://query.wikidata.org/sparql")
sparql.setQuery(query_string)
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
done = True
except HTTPError:
time.sleep(10)
results_df = pd.json_normalize(results['results']['bindings'])
if results_df.empty:
return None
return results_df['countyLabel.value'].iloc[0]
def find_ireland(place_str):
"""
Function that searches wikipedia for a specific Irish loction
and returns the tuple (county, whether Ireland or Northern Ireland, UK) if the place is found
else it return (None, None, None)
"""
done = False
while done == False:
try:
results = wikipedia.search(place_str, results = 5)
done = True
except ConnectionError:
time.sleep(10)
#Search for county if not results
if len(results) == 0:
for place in place_str:
if 'County' or 'county' in place:
results = wikipedia.search(place, results = 5)
break
if len(results) == 0:
return None, None, None
try:
url = wikipedia.page(results[0]).url
except PageError:
return None, None, None
except DisambiguationError:
return None, None, None
except:
return None, None, None
wikidata_url = return_wikidata_identifier_from_wikipedia_page(url)
if wikidata_url == None:
return None, None, None
place_str = wikidata_url.split('/')[-1]
county = wikidata_search_irish_county(place_str)
if 'County' in county:
county = county.replace('County', '')
county = county.strip()
northern_Ireland_counties = ['Antrim', 'Armagh', 'Down', 'Fermanagh', 'Londonderry', 'Tyrone', 'Derry']
Ireland_counties = ['Cork', 'Galway', 'Mayo', 'Donegal', 'Kerry', 'Tipperary', 'Clare', 'Tyrone', 'Antrim', 'Limerick', 'Roscommon', 'Down',
'Wexford', 'Meath', 'Londonderry', 'Kilkenny', 'Wicklow', 'Offaly', 'Cavan', 'Waterford', 'Westmeath', 'Sligo', 'Laois', 'Kildare', 'Fermanagh',
'Leitrim', 'Armagh', 'Monaghan', 'Longford', 'Dublin', 'Carlow', 'Louth']
if county in northern_Ireland_counties:
ireland = 'Northern Ireland'
country = 'UK'
elif county in Ireland_counties:
ireland = None
country = 'Republic of Ireland'
county = None
else:
return None, None, None
return county, ireland, country
def return_historic_county(place, place_broken_up, col = 'place20nm', df = index_of_places):
"""
Function that returns the historical county and British country (Wales, England, Scotland) of the place passed in
by quering the Index of Places database for the place passed in
"""
#Find place in the index of places
filtered_df = df.loc[df[col] == place]
#If more than one exact match, then use the other columns and the rest of place to see which match the best
if len(filtered_df) > 1:
if len(place_broken_up) > 2:
place_broken_up.remove(place)
if place in place_broken_up:
print(True)
for place in place_broken_up:
try:
if place != 'United Kingdom' and place != 'UK':
filtered_df_ = filtered_df[filtered_df.apply(lambda r: r.str.contains(place, case=False, na = None).any(), axis=1)]
if len(filtered_df_) != 0:
filtered_df = filtered_df_
except:
return None, None
#If still more, take the one with most information that describes the largest place
if len(filtered_df) > 1:
filtered_df_ = filtered_df[filtered_df['ctyhistnm'].notna()]
if filtered_df_.empty:
try:
filtered_df = filtered_df[filtered_df['descnm'] == 'CTYHIST']