forked from tuub/oa-eval
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1629 lines (1405 loc) · 67 KB
/
main.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
#!/usr/bin/env python3.7
# -*- coding: utf-8 -*-
###############################################################################
# This work is distributed under a BSD 3-Clause License.
# license terms see https://opensource.org/licenses/BSD-3-Clause
# developed mainly by Eva Bunge (ORCiD:0000-0002-5587-5934, github.com/ebunge)
# with support from Michaela Voigt (ORCiD:0000-0001-9486-3189,
# github.com/michaelavoigt) and maintained by the Open Access team of
# TU Berlin University Library
###############################################################################
import numpy as np
import collections
import pickle
import weakref
from prettytable import PrettyTable
import urllib.request
import urllib.error
import json
import os
import re
import itertools
from data_corrections_berlin_2019 import replace_incorrect_dois
# ----------------- 1. Enable/Disable Functionalities -------------------------
# Detailed instructions for querying databases and preparing DOAJ data
# are included in the manual (in German).
# These variables are used to run only certain parts of the script. Set
# them all to 'True' to run the whole script.
# doAnalysis: If True - do some statistics and analysis of the final data. If
# False - disable this feature.
# doReadIn: If True - read in the database data from the text files and save it
# to file 'finalList'. If False - data is loaded from file 'finalList'
doAnalysis = True
doReadIn = True
# Variable that determines whether to contact CrossRef. Possible values:
# 1: Contact the CrossRef API to add missing ISSNs. Write results to file.
# 2: Read results from previously created file instead
# 0: Disable this feature
contactCR = 0
# Variable that determines whether to contact Unpaywall in order to retrieve
# data on green and hybrid OA. Possible values:
# 1: Contact the Unpaywall-API to retrieve OA-article-data. Write results to file.
# 2: Read results from previously created file instead
# 0: Disable this feature
contactOaDOI = 0
# Decide what to do when a corresponding/first author of a publication can't be
# determined manually. Possible values:
# 1: Write all of those articles to a file (docsToBeChecked.txt).
# Once you have determined which aricles have a first/corresponding author
# from a relevant institution, save the data in a tab-delimited, utf8-
# encoded text-file called 'docsChecked.txt', with the following format:
# each line corresponds to an article and the three columns contain (in this
# order): title, DOI, name of institution (which should be spelled identical
# to the name of the institution as set up in this script = 'inst.name')
# Place this file in the subfolder 'input-files'
# 2: Load this information into the script and have it included in the final
# results and the statistic.
# 0: Disable this feature completely.
checkToDo = 1
# Clarify which years of publication are of interest to you
yearMin = 2019
yearMax = 2019
# Enter your email here. It's needed to contact Unpaywall
myEMail = '[email protected]'
# ----------------- 2. Setting up Classes and Functions -----------------------
# Set up class for institutions
class Inst(object):
instances = []
nameVar1 = None
def __init__(self, name, nameVariants):
self.__class__.instances.append(weakref.proxy(self))
self.name = name
self.nameVar = nameVariants
# Set up class for databases
class Database(object):
instancesdb = []
content = None
def __init__(self, name, idNummer):
self.__class__.instancesdb.append(weakref.proxy(self))
self.name = name
self.idNummer = idNummer
def save_publications_data_to_file(document_list, filename_out):
print('save data to ' + filename_out)
if os.path.exists(filename_out):
os.remove(filename_out)
with open(filename_out, 'w', encoding='utf-8') as f:
ch = 'authors\ttitle\tOA-Status\tDOI\tjournal\tISSN\teISSN\tpublisher\tyear\t' + \
'affiliations\tall identified name variants\tcorresponding author\t' + \
'found name variant\te-mail\tsubject\tDOAJ subject\tfunding\tlicence\t' + \
'databaseID\tnotes\toaDOI[is_oa]\toaDOI[journal_is_oa]\toaDOI[host_type]\t' + \
'oaDOI[license]\tAPC Amount\tAPC Currency\tnotes'
f.write(ch + '\n')
for d in document_list:
document_data = []
for i in d.arry():
if i is None:
result_string = 'None'
else:
result_string = re.sub('[\t\n\r]', ' ', str(i).strip())
document_data.append(result_string)
f.write('\t'.join(document_data))
f.write('\n')
# Set up class for documents
class Document(object):
nameVariant = None
allNameVariants = None
doajSubject = None
lizenz = None
oaStatus = None
APCValue = None
APCCurrency = None
checks = ''
oaDOI1 = ''
oaDOI2 = ''
oaDOI3 = ''
oaDOI4 = ''
notes = '' # Bearbeitungsnotizen
def __init__(self, authors, title, DOI, journal, ISSN, eISSN, publisher,
year, affiliations, corrAuth, eMail, subject, funding, dbID):
self.authors = authors
self.title = title
self.DOI = DOI
self.journal = journal
self.ISSN = ISSN
self.eISSN = eISSN
self.publisher = publisher
self.year = year
self.affiliations = affiliations
self.corrAuth = corrAuth
self.eMail = eMail
self.subject = subject
self.funding = funding
self.dbID = dbID
# Return first three consonants of the author's name concatenated with the
# first 19 consonants of the title
def konsonanten(self):
d = ' '.join([''.join([i for i in self.authors if i in co]).lower()[0:3],
''.join([i for i in self.title if i in co]).lower()[0:19]])
return d
# Return all values associated with a certain publication
def arry(self):
return [self.authors, self.title, self.oaStatus, self.DOI,
self.journal, self.ISSN, self.eISSN, self.publisher, self.year,
self.affiliations, self.allNameVariants, self.corrAuth,
self.nameVariant, self.eMail, self.subject, self.doajSubject,
self.funding, self.lizenz, dbNameID[self.dbID], self.checks,
self.oaDOI1, self.oaDOI2, self.oaDOI3, self.oaDOI4,
self.APCValue, self.APCCurrency, self.notes]
# Function that takes consonants from a title and turns them into a string
# INPUT: title of a publication (string)
# OUTPUT: first twenty consonants of the title (string)
def kons(title):
d = ''.join([item for item in title if item in co]).lower()[0:19]
return d
# Function that checks if an ISSN/eISSN is in the DOAJ and adds doaj-data
# to the document
# INPUT: List of documents to be checked, case = 1 in general, case = 2 if
# finalList is being read in from a file
def checkISSN(docList, case):
for item in docList:
test1 = (item.ISSN in eissns or item.ISSN in issns)
test2 = (item.eISSN in eissns or item.eISSN in issns)
test3 = False
if test1:
t1 = [rec for rec in doaj if rec[0] == item.ISSN]
if t1 == []:
t1 = [rec for rec in doaj if rec[1] == item.ISSN]
test3 = int(t1[0][8]) <= int(item.year)
elif test2:
t1 = [rec for rec in doaj if rec[0] == item.eISSN]
if t1 == []:
t1 = [rec for rec in doaj if rec[1] == item.eISSN]
test3 = int(t1[0][8]) <= int(item.year)
if test3:
if (item.ISSN is not None and test1) \
or (item.eISSN is not None and test2):
if case == 1:
item.oaStatus = 'gold'
item.checks += 'Identified via DOAJ '
if t1[0][4] != '':
item.APCValue = t1[0][4]
item.APCCurrency = t1[0][5]
elif case == 2:
doc = [x for x in finalList if x.DOI == item.DOI]
doc[0].oaStatus = 'gold'
doc[0].checks += 'Identified via DOAJ '
if t1[0][4] != '':
doc[0].APCValue = t1[0][4]
doc[0].APCCurrency = t1[0][5]
if test1:
j = np.where(doaj == item.ISSN)
elif test2:
j = np.where(doaj == item.eISSN)
item.doajSubject = str(doaj[j[0], 3]).strip("['").strip("']")
item.publisher = str(doaj[j[0], 6]).strip("['").strip("']").strip()
if '\n' in item.publisher:
item.publisher = ''.join([s for s in item.publisher
if s != '\n'])
item.lizenz = str(doaj[j[0], 7]).strip("['").strip("']")
return
# Function to identify corresponding authors (= first authors) in Inspec data
# INPUT: list of authors of a publication, list of their affiliations
# OUTPUT: first author; associated affiliation (string)
def inspecCorrAuth(auth, affil):
authorList = auth.split('; ')
affilList = affil.split('; ')
if authorList[0] in affilList:
firstAuth = affilList.index(authorList[0])
else:
return None
while firstAuth < len(affilList) and affilList[firstAuth] in authorList:
firstAuth += 1
if firstAuth + 1 == len(affilList):
tempor = affilList[-1]
elif firstAuth < len(affilList):
tempor = affilList[firstAuth].split('.')[:-2]
return authorList[0] + '; ' + ''.join(tempor)
# Function that takes a list of documents and contacts CrossRef to find
# missing ISSNs/eISSNs
# INPUT: List of documents that have a DOI but no ISSN of eISSN
def askCR(missISSN):
print('Begin contacting CrossRef')
c = 0
reCheck = []
baseurl = 'http://api.crossref.org/works/'
for doc in missISSN:
doi = doc.DOI
myurl = baseurl + doi
try:
response = urllib.request.urlopen(myurl)
cr_data = json.load(response)
cr_data_msg = cr_data["message"]
if "ISSN" in cr_data_msg:
c += 1
reCheck.append(doc)
doc.ISSN = str(cr_data_msg["ISSN"][0])
if len(cr_data_msg["ISSN"]) > 1:
doc.eISSN = str(cr_data_msg["ISSN"][1])
except urllib.error.HTTPError as err:
fehler = "Sorry, something went wrong with CrossRef (HTTP Error)."
print(fehler)
print(str(c) + ' ISSNs added via CrossRef')
return reCheck
# Contacts the Unpaywall-API to retrieve data on green / hybrid (& gold) OA
# status. Also retrieve publisher data if provided.
# INPUT: List of publications that have a DOI but whose ISSN is not listed in
# the DOAJ
# OUTPUT: Results printed to file oaDOI-response.txt: one line per publication,
# containing the following information: DOI, is_oa, journal_is_oa,
# host_type [repository or publisher], license, publisher, oaStatus
def askOaDOI(needInfo):
print('Begin contacting Unpaywall')
baseurl = 'https://api.unpaywall.org/v2/'
relKeys = {1: 'is_oa', 2: 'journal_is_oa', 3: 'host_type', 4: 'license',
5: 'publisher'}
replies = [[0 for x in range(7)] for y in range(len(needInfo))]
i = 0
errDOIs = []
for doc in needInfo:
doi = doc.DOI
replies[i][0] = doi
myurl = baseurl + doi + '?email=' + myEMail
try:
response = urllib.request.urlopen(myurl)
response = json.load(response)
for item in relKeys:
if relKeys[item] in response:
replies[i][item] = response[relKeys[item]]
# if the key cannot be found in the response (on the top level)
# but there is an entry 'best_oa_location' that has an entry for
# that key then take that value.
elif 'best_oa_location' in response:
subresponse = response['best_oa_location']
if subresponse is not None:
replies[i][item] = subresponse[relKeys[item]]
if replies[i][1] and replies[i][2]:
doc.oaStatus = 'gold'
doc.checks += 'Identified via Unpaywall '
elif replies[i][1] and not replies[i][2] \
and replies[i][3] == 'repository':
doc.oaStatus = 'green'
doc.checks += 'Identified via Unpaywall '
elif replies[i][1] and not replies[i][2] \
and replies[i][3] == 'publisher':
if 'cc' in str(replies[i][4]):
doc.oaStatus = 'hybrid'
doc.checks += 'Identified via Unpaywall '
doc.oaDOI1 = replies[i][1]
doc.oaDOI2 = replies[i][2]
doc.oaDOI3 = str(replies[i][3])
doc.oaDOI4 = str(replies[i][4])
doc.lizenz = str(replies[i][4])
doc.publisher = str(replies[i][5])
replies[i][6] = doc.oaStatus
except urllib.error.HTTPError as err:
fehler = "Sorry, Unpaywall doesn't know this DOI (HTTP Error)."
print('DOI ', doi, ': ', fehler)
errDOIs += [doi]
except:
print('DOI ', doi + ': ++++++++ other error!! ++++++++ ')
i += 1
if i % 500 == 0:
print('Now received responses for ', i, ' documents from Unpaywall')
ch = 'DOI\tis_oa\tjournal_is_oa\thost_type\tlicense\tpublisher\toaStatus'
np.savetxt('output-files/oaDOI-response.txt', replies, delimiter='\t',
header=ch, comments='', fmt='"%s"')
np.savetxt('output-files/DOIs-oaDOI-error.txt', errDOIs, delimiter='\t',
header='DOIs causing error at Unpaywall-API', comments='',
fmt='"%s"')
print('Saved Unpaywall-responses to file "oaDOI-responses.txt"')
return
# Function that takes data in WoS-format and transforms the data into a list of
# Document-objects.
# !This function is not really needed in this script as it is right now!
# It's being included for the purpose of easily adding new databases to the
# script. To do this export article data from Citavi in the WoS-format and use
# this function to do the read-in for the data
# INPUT: (list of records in WoS-format, database ID (integer))
# OUTPUT: list of Document-objects
def wosFormat(wosRecords, ind):
records = []
i = 0
with open(wosRecords, 'r', newline=None) as f:
for line in f:
if i == 0:
newDoc = Document('', '', None, None, None, None,
None, None, '', None, None, None, None, ind)
i += 1
le = len(line)
if line[0:2] != ' ':
kuerzel = line[0:2]
if line[0:2] == 'TI':
newDoc.title = line[3:le].strip('\n').strip('\r')
elif line[0:2] == 'SO':
newDoc.journal = line[3:le].strip('\n').strip('\r')
elif line[0:2] == 'PY':
newDoc.year = line[3:le].strip('\n').strip('\r')
elif line[0:2] == 'SN':
if '-' not in line:
vorl = line[3:le].strip('ISSN ').strip('\n').strip('\r')
newDoc.ISSN = vorl[0:4] + '-' + vorl[4:8]
elif ',' in line:
newDoc.ISSN = line.strip('ISSN ').strip('\n').strip('\r')[0:9]
else:
newDoc.ISSN = line[3:le].strip('ISSN ').strip('\n').strip('\r')
elif line[0:2] == 'DI':
newDoc.DOI = line[3:le].strip('\n').strip('\r')
elif line[0:2] == 'AF':
newDoc.authors = line[3:le].strip('\n').strip('\r')
elif kuerzel == 'AF' and line[0:2] == ' ':
newDoc.authors += '; '
newDoc.authors += line[3:le].strip('\n').strip('\r')
elif line[0:2] == 'FN':
records.append(newDoc)
newDoc = Document('', '', None, None, None, None,
None, None, '', None, None, None, None, ind)
records.append(newDoc)
return records
# Checks a given name of an institution against a list of approved name
# variants and returns the names of institutions that have been identified.
# INPUT: (text string with name of an institution, case 0 = corresponding
# author | case 1 = general affiliations)
# OUTPUT: (bool stating if instition is part of approved list, names of
# institutions that have been found)
def listCheck(institution, case):
val = [None] * len(institutions)
variant = None
for i in range(0, len(val)):
if case == 0:
instList = institutions[i].nameVar
elif case == 1:
instList = institutions[i].nameVar1
valu = [None] * len(instList)
for j in range(0, len(instList)):
valu[j] = all(word in institution for word in instList[j])
if any(valu):
if variant is None:
variant = institutions[i].name
else:
variant += '; ' + institutions[i].name
val[i] = True
return (any(val), variant)
# Function that takes data in PubMed-format and transforms it into a list of
# Documents.
# INPUT: (PubMed-records, database ID (integer))
# OUTPUT: list of Documents
def pubmedFormat(pmRecords, ind):
records = []
i = 0
authorCount = 0
newDoc = None
with open(pmRecords, 'r', newline=None) as f:
for line in f:
lengths = len(line)
if line[0:2] != ' ':
kuerzel = line[0:4]
if line[0:4] == 'PMID':
authorCount = 0
if i > 0:
records.append(newDoc)
newDoc = Document('', '', None, None, None, None,
None, None, '', None, None, None, None, ind)
i += 1
elif line[0:2] == 'TI':
newDoc.title = line[6:lengths].strip('\n').strip('\r')
elif kuerzel == 'TI ' and line[0:2] == ' ':
newDoc.title += ' '
newDoc.title += line[6:lengths].strip('\n').strip('\r')
elif line[0:2] == 'IS' and line[-5:-2] == 'nic':
newDoc.eISSN = line[6:15]
elif line[0:2] == 'IS' and line[-5:-2] == 'ing':
newDoc.ISSN = line[6:15]
elif line[0:3] == 'FAU' and authorCount > 0:
newDoc.authors += '; '
newDoc.authors += line[6:lengths].strip('\n').strip('\r')
authorCount += 1
elif line[0:3] == 'FAU' and authorCount == 0:
newDoc.authors = line[6:lengths].strip('\n').strip('\r')
newDoc.corrAuth = newDoc.authors + '; '
authorCount += 1
elif authorCount == 1 and line[0:2] == 'AD':
newDoc.corrAuth += line[6:lengths].strip('\n').strip('\r')
newDoc.affiliations = line[6:lengths].strip('\n').strip('\r')
elif line[0:2] == ' ' and kuerzel == 'AD ' and authorCount == 1:
newDoc.affiliations += line[5:lengths].strip('\n').strip('\r')
newDoc.corrAuth += line[5:lengths].strip('\n').strip('\r')
elif line[0:2] == ' ' and kuerzel == 'AD ' and authorCount > 1:
newDoc.affiliations += line[5:lengths].strip('\n').strip('\r')
elif authorCount > 1 and line[0:2] == 'AD':
newDoc.affiliations += '; '
newDoc.affiliations += line[5:lengths].strip('\n').strip('\r')
elif line[0:2] == 'JT':
newDoc.journal = line[6:lengths].strip('\n').strip('\r')
elif line[0:2] == 'DP':
newDoc.year = line[6:10]
elif line[0:3] == 'LID' and 'doi' in line:
newDoc.DOI = line[6:lengths].strip('\n').strip('\r').strip(' [doi]')
records.append(newDoc)
return records
# Read in table mapping RIS-fields of databases to document-attributes
risFields = np.genfromtxt('RIS-fields.csv', delimiter=';', dtype=None, encoding='utf-8')
# Valid characters for ISSNs
numX = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'X']
def concatenate_tags(publication, tag_list):
# just concatenate the strings belonging to the tags in the tag_list; separate values with '; '
result_list = []
for tag in tag_list:
if tag in publication: # wenn Tag in Publications-Daten vorhanden
result_list.extend(publication[tag])
if result_list:
return '; '.join(result_list)
else:
return None
def get_first_author_and_first_affiliation_as_string(newDoc):
result_list = []
att_authors = getattr(newDoc, 'authors')
att_affiliations = getattr(newDoc, 'affiliations')
if att_authors:
# if more than one author: normally separated by ;
first_author = att_authors.split('; ')[0]
result_list.append(first_author)
if att_affiliations:
# if more than one affiliation: normally separated by ;
first_affiliation = att_affiliations.split('; ')[0]
result_list.append(first_affiliation)
return '; '.join(result_list)
# Read in RIS-files
# INPUT: RIS-records, database-ID
# OUTPUT: List of documents
def risFormat(risRecords, ind):
records = []
#
# read file, put data in data structure
#
publication_data = []
with open(risRecords, 'r', newline=None) as f:
for line in f:
if line.strip(): # ignore empty lines
tag = line[0:2]
data = line[6:-1].strip()
# ignore lines that do not match the pattern "XX - data"
if not (tag.isupper() and line[2] == ' '):
continue
# ignore line with Tag 'TY' for database CINAHL
if ind == 12 and tag == 'TY':
continue
# Start of a new record?
if (ind != 12 and tag == 'TY') or (ind == 12 and tag == 'ID'):
publication_data.append({})
# enter line in data list
# is there an entry for that tag?
if not tag in publication_data[-1]:
publication_data[-1][tag] = []
publication_data[-1][tag].append(data)
#
# Auswertung
#
# get col from file RIS-fields.csv
ris_tags = {}
for col_nr_db in range(len(risFields[0])):
if str(ind) == risFields[0][col_nr_db]:
break
# get RIS-Tags for fields
for line_nr in range(1, len(risFields)):
attribute = risFields[line_nr][0]
if not attribute in ris_tags:
ris_tags[attribute] = []
if risFields[line_nr][col_nr_db]: # falls Feld nicht leer
ris_tags[attribute].append(risFields[line_nr][col_nr_db])
#
# extract data for each publication
#
for publication in publication_data:
newDoc = Document('', '', None, None, None, None, None, None, '', None, None, None, None, ind)
records.append(newDoc)
# take fields as is; concatenate with ; if several tags
for attribute in ['authors', 'title', 'journal', 'publisher']:
result_string = concatenate_tags(publication, ris_tags[attribute])
if attribute == 'title' and result_string:
result_string = result_string.strip('.')
setattr(newDoc, attribute, result_string)
result_string = None
# affiliations
attribute = 'affiliations'
if ind in [9, 13, 17]: # BSC, EBSCO, SportDiscus
# nehme Affiliatin aus 'AD', wenn vorhanden, sonst 'N1'
for tag in ris_tags[attribute]:
if tag in publication: # wenn Tag in Publications-Daten vorhanden
# Affiliationen stehen häufig im Notiz-feld N1; ist aber Fallback, nehme N1 nur,
# wenn es kein anderes Feld gibt!
if tag != 'N1':
attribute_string = '; '.join(publication[tag])
setattr(newDoc, attribute, attribute_string)
break # danach keine weiteren Tags mehr auswerten!
elif tag == 'N1':
attribute_string = '; '.join(publication[tag])
# Affiliationen stehen im Notizfeld zusammen mit anderen Angaben
# wird mit "Affiliations: " eingeleitet
# angaben danach eingeleitet mit : 'Source Info:', 'Issue Info:', 'Document Type:' oder 'Release Date:'
m = re.search('Affiliations?: +(.+?) +(Source Info:|Issue Info:|Document Type:|Release Date:|No. of Pages:)', attribute_string)
if m:
substring = m.group(1)
if ind in [17]: # SportDiscus
# split into affiliations; each is marked by : 1 ,: 2 , etc,
affiliations_list = re.split(": [0-9]+ ", ': ' + substring)
else:
# split into affiliations; each is marked by 1: , 2: , etc,
# important: there must be whitespace ahead of the number; otherwise the match might be incorrect
affiliations_list = re.split("\s[0-9]+\s*:\s*", ' ' + substring)
new_affiliations_string = ''
for aff in affiliations_list:
if aff.strip(): # ignore empty entries
aff = aff.strip(' ;') # strip ; from end
if new_affiliations_string:
new_affiliations_string += '; '
new_affiliations_string += aff
setattr(newDoc, attribute, new_affiliations_string)
else:
setattr(newDoc, attribute, concatenate_tags(publication, ris_tags[attribute]))
# DOI
attribute = 'DOI'
result_string = ''
if ind in [13]:
for tag in ris_tags[attribute]:
if tag in publication: # wenn Tag in Publications-Daten vorhanden
if tag != 'N1':
for attribute_string in publication[tag]:
if 'doi.org' in attribute_string or attribute_string.startswith('10.'):
result_string = attribute_string
break # nehme nur die erste DOI
if result_string: # falls Ergebnis, ddanach keine weiteren Tags mehr auswerten!
break
else: # N1
attribute_string = '; '.join(publication[tag])
m = re.search('DOI: +([^\s]+)', attribute_string)
if m:
result_string = m.group(1).strip(' .')
if result_string.strip():
result_string = result_string.strip()
if 'doi.org' in result_string:
result_string = result_string[result_string.find('doi.org') + 8:]
setattr(newDoc, attribute, result_string)
else:
result_string = concatenate_tags(publication, ris_tags[attribute])
if result_string and 'doi.org' in result_string:
result_string = result_string[result_string.find('doi.org') + 8:]
setattr(newDoc, attribute, result_string)
result_string = None
# ISSN, eISSN
attribute = 'ISSN'
for tag in ris_tags[attribute]:
if tag in publication: # wenn Tag in Publications-Daten vorhanden
for attribute_string in publication[tag]: # falls es mehrere Tags gibt
if attribute_string[0:4] != '978-':
# anInt = filter(lambda x: x in numX, attribute_string.split())
anInt = ''.join(filter(lambda x: x in numX, attribute_string))
if anInt != '':
# das erste Tag
if getattr(newDoc, attribute) in ('', None):
setattr(newDoc, attribute, anInt[0:4] + '-' + anInt[4:8])
if len(anInt) > 8:
setattr(newDoc, 'eISSN', anInt[8:12] + '-' + anInt[12:16])
# zweites Tag = Elektronisch
else:
setattr(newDoc, 'eISSN', anInt[0:4] + '-' + anInt[4:8])
# year
attribute = 'year'
for tag in ris_tags[attribute]:
if tag in publication: # wenn Tag in Publications-Daten vorhanden
attribute_string = publication[tag][0] # nehme das erste Tag, ignoriere weitere
if len(attribute_string) > 4:
result = int(attribute_string[:4]) # beginnt mit der Jahreszahl
else:
result = int(attribute_string)
setattr(newDoc, attribute, result)
# corrAuth
attribute = 'corrAuth'
if ris_tags[attribute]: # if defined in RIS-fields.csv
if ind in [16]: # Scopus
result_list = []
for tag in ris_tags[attribute]:
if tag in publication: # wenn Tag in Publications-Daten vorhanden
for attribute_string in publication[tag]:
m = re.search('Correspondence Address: (.+)$', attribute_string)
if m:
result_list.append(m.group(1))
if result_list:
result_string = '; '.join(result_list)
else: # nothing found in tags
result_string = get_first_author_and_first_affiliation_as_string(newDoc)
setattr(newDoc, attribute, result_string)
result_string = None
result_list = None
else:
setattr(newDoc, attribute, concatenate_tags(publication, ris_tags[attribute]))
else:
# take first author + first affiliation
# but only if the database has information about affiliations (otherwise useless)
if getattr(newDoc, 'affiliations'):
setattr(newDoc, attribute, get_first_author_and_first_affiliation_as_string(newDoc))
# eMail
attribute = 'eMail'
if ind in [9, 13, 17]: # BSC, EBSCO, SportDiscus
# Mail address in notes N1
result_string = ''
attribute_string_list = []
for tag in ris_tags['affiliations']:
if tag in publication: # wenn Tag in Publications-Daten vorhanden
# Affiliationen stehen häfig im Notiz-feld N1; ist aber Fallback, nehme N1 nur, wenn es kein anderes Feld gibt!
attribute_string_list.extend(publication[tag])
if tag != 'N1':
break # danach keine weiteren Tags mehr auswerten!
m = re.search('(Email Address|email): ([^\s;]+)', '; '.join(attribute_string_list))
if m:
result_string = m.group(2).strip(' ,;.')
if result_string:
setattr(newDoc, attribute, result_string)
result_string = None
elif ind in [14, 16]: # Embase, Scopus
result_list = []
for tag in ris_tags['corrAuth']: # part of the field that contains the corresponding author
if tag in publication: # wenn Tag in Publications-Daten vorhanden
for attribute_string in publication[tag]:
m = re.search('(E-mail|email): (.+)$', attribute_string)
if m:
result_list.append(m.group(2))
if result_list:
setattr(newDoc, attribute, '; '.join(result_list))
result_list = None
return records
# List of consonants
co = ('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r',
's', 't', 'v', 'w', 'x', 'y', 'z', 'B', 'C', 'D', 'F', 'G', 'H', 'J',
'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z')
# Duplicate check
# This function takes a set of data (= masterList) and compares incoming new
# data with it. All duplicates are removed from the new data which is then
# added to the masterList. This action is repeated for each database.
# Comparisons are done via DOI-matching and then title/author-matching.
# doiList = list that contains all DOIs from masterList.
# konsMast = a list of strings which consist of the first three consonants of
# the authors' names and the first 19 consonants of the title for the data
# in the masterlist.
# INPUT: (iterating integer, list containing article data,
# list of DOIs (strings), list of strings for title/author-matching)
# OUTPUT: list containing Documents with duplicates removed
def dubletten(iterates, masterList, dois, kons):
nowList = datenbanken[iterates].content
if iterates == 1:
doiList = [x.DOI for x in masterList]
konsMast = [item.konsonanten() for item in masterList]
else:
doiList = dois
konsMast = kons
f = collections.Counter(konsMast)
i = len(nowList)
print(datenbanken[iterates].name, ' - number of records: ', i)
nowList = [item for item in nowList if item.DOI is None
or item.DOI.strip('"') == ''
or item.DOI.strip('"') not in doiList]
j = len(nowList)
print(datenbanken[iterates].name, \
' - number of records removed via DOI-matching: ', i-j)
nowList_before_removal_author_title = nowList.copy()
nowList = [item for item in nowList if item.authors is not None
and item.konsonanten() not in f]
# the duplicates that are removed may have a DOI while the remaining duplicate does not have one.
# in this case copy the DOI of the removed duplicate to the reamining item
removed_by_author_title_with_DOI = [x for x in nowList_before_removal_author_title if x not in nowList and x.DOI]
removed_temp = {}
for item in removed_by_author_title_with_DOI:
removed_temp[item.konsonanten()] = item
for item in masterList:
if item.konsonanten() in removed_temp:
if not item.DOI and removed_temp[item.konsonanten()].DOI:
item.DOI = removed_temp[item.konsonanten()].DOI
item.notes += 'DOI added from duplicate! '
print ('---- DOI added from duplicate!')
k = len(nowList)
print(datenbanken[iterates].name, \
' - number of records removed via title/author-matching: ', j-k)
print(datenbanken[iterates].name, \
' - number of records added to masterList: ', k)
if k > 0:
masterList += nowList
doiList += [x.DOI for x in nowList]
konsMast += [item.konsonanten() for item in nowList]
iterates += 1
if iterates < len(datenbanken):
masterList = dubletten(iterates, masterList, doiList, konsMast)
return masterList
# -------------------- 3. Set up Institutions ---------------------------------
# Set up institutions. Format for name variants:
# [[var1,var2],[var3]] is equivalent to: (var1 AND var2) OR (var3)
# Careful: the name variant used when querying the database is not
# necessarily the same name variant used in the raw data.
# TU
TUnames = [['Tech', 'Univ', 'Berlin'], ['Berlin', 'TU'],
['Berlin', 'Inst', 'Technol']]
TU = Inst('TU', TUnames)
# Charité
Cnames = [['Charit', 'Univ'],
['Campus', 'Virchow', 'Berlin'],
['Campus', 'Franklin', 'Berlin'],
['Campus', 'Buch', 'Berlin'],
['Campus', 'Mitte', 'Berlin'],
['Charit', 'Berlin'],
['Berlin', 'Inst', 'Health'],
['Berlin', 'Inst', 'Gesundheitsforschung'],
['medizin', 'Berlin'],
['Medical', 'Univ', 'Berlin'],
['Medical', 'School', 'Berlin']]
Charite = Inst('Charité', Cnames)
# TODO: Univ Med Berlin = Charité?
# FU
FUnames = [['Berlin', 'FU'], ['Berlin', 'Free Univ'],
['Berlin', 'Freie', 'Univ'], ['Univ', 'Libre', 'Berlin']]
FU = Inst('FU', FUnames)
# TODO: not recognized
#
# Frei Univ Berlin
# Frei Universität Berlin
# Frei Universitaet Berlin
# HU
HUnames = [['Berlin', 'HU'],
['Berlin', 'Humboldt', 'Univ']]
HU = Inst('HU', HUnames)
# TODO: not recognized
#
# Humboldt University
# Humboldt-Universität
# Humboldt University
# Humbolt Univ Berlin
# UdK
UdKnames = [['Univ', 'Arts', 'Berlin'],
['Univ', 'Kunst', 'Berlin'],
['Berlin', 'UdK']]
UdK = Inst('UdK', UdKnames)
# TODO: not recognized
#
# Universität der Künste, Berlin
# Universität der Künste Berlin
# Beuth
Bnames = [['Beuth', 'Berlin']]
Beuth = Inst('Beuth', Bnames)
# HTW
HTWnames = [['HTW', 'Berlin'],
['Tech', 'Wirt', 'Berlin']]
HTW = Inst('HTW', HTWnames)
# HWR
HWRnames = [['HWR', 'Berlin'],
['Wirt', 'Recht', 'Berlin'],
['Berlin', 'Economics', 'Law', 'School']]
HWR = Inst('HWR', HWRnames)
# TO DO: not recognized
# Berlin Sch Econ & Law, Berlin
# Alice Salomon
ASHnames = [['Alice', 'Salomon', 'Berlin'], ['ASH', 'Berlin'],
['Universidad Alice Salomon']]
ASH = Inst('ASH', ASHnames)
# Create list of institutions
institutions = [x for x in Inst.instances]
# If the name of the institution is very generic, a second set of name
# variants can be defined here. These are used when searching strings with
# more than one affiliation in them
for item in institutions:
item.nameVar1 = item.nameVar
TU.nameVar1 = [['Technische Universitat Berlin'],
['Technische Universitaet Berlin'],
['Technische Universität Berlin'],
['Berlin Institute of Techn'],
['Tech Univ Berlin'],
['Berlin Univ Technol'],
['Univ Technol Berlin'],
['TU Berlin'],
['Tech. Univ. Berlin'],
['Technical Univ. of Berlin'],
['Berlin Inst Technol'],
['Technical University Berlin'],
['Technische Universitaet de Berlin'],
['Technical University of Berlin'],
['Berlin University of Technology']]
# TODO: not recognized
#
# Tech Univ, Fachgebiet Bauinformat, Berlin, Germany
# Technol Univ Berlin
# Tech Univ, Berlin
# Berlin Tech Univ
# TU, Berlin
# Technical University (TU) Berlin
# Technischen Universität Berlin
# Technische Universität, Berlin
# Technische Univerisitaet Berlin
# Berlin, TU
# Technical University, Berlin
# Tech. Univ., Berlin
# Technical University in Berlin
# ------------- 4. Read in Text Files and Extract Information -----------------
# Set up databases
# The order of the databases here determines the order in which they are
# considered. Therefore databases with good/complete metadata should be near
# the top
dbWoS = Database('Web of Science', 1)
dbSF = Database('SciFinder', 2)
dbPM = Database('PubMed', 3)
dbScopus = Database('Scopus', 16)
dbInspec = Database('Inspec', 5)