Skip to content

Commit 1d3f86c

Browse files
dracosTheyWorkForYou Live CVS User
authored andcommitted
Upgrade python 2 to 3.
1 parent f8f73ad commit 1d3f86c

75 files changed

Lines changed: 934 additions & 999 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

filtersentence_xml.py

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,10 @@
1-
#! /usr/bin/python
2-
31
from datetime import datetime
42
import re
5-
import string
63

74
from lxml import etree
85

96
from contextexception import ContextException
107
from parlphrases import parlPhrases
11-
12-
from wrans.emblinks import rreglink, rregemail, rehtlink, ConstructHTTPlink
13-
148
from resolvemembernames import memberList
159

1610

@@ -81,12 +75,12 @@ def TokenStandingOrder(mstandingo, phrtok):
8175
'phrase', ' class="standing-order" code="%s"' % mstandingo.group(1)
8276
)
8377

78+
rehtlink = re.compile('(?<!["\'])(https?://)([^\s]+)')
8479

8580
def TokenHttpLink(mhttp, phrtok):
86-
qstrlink = ConstructHTTPlink(mhttp.group(1), mhttp.group(2), mhttp.group(3))
81+
qstrlink = mhttp.group(0)
8782
return ('a', ' href="%s"' % qstrlink)
8883

89-
9084
def TokenHrefLink(mhttp, phrtok):
9185
return ('', '')
9286

@@ -118,8 +112,8 @@ def TokenOffRep(qoffrep, phrtok):
118112
qcolnum = qcpart.group(1)
119113
if qcpart.group(2):
120114
qcpartlead = qcpart.group(1)[len(qcpart.group(1)) - len(qcpart.group(2)):]
121-
if string.atoi(qcpartlead) >= string.atoi(qcpart.group(2)):
122-
print ' non-following column leadoff ', qoffrep.group(0)
115+
if int(qcpartlead) >= int(qcpart.group(2)):
116+
print(' non-following column leadoff ', qoffrep.group(0))
123117
# raise Exception, ' non-following column leadoff '
124118

125119
if qcolsuffix == 'WH':
@@ -312,4 +306,4 @@ def GetPara(self):
312306
else:
313307
res.append(tok[2])
314308

315-
return string.join(res, '')
309+
return ''.join(res)

get-historic-debates

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import requests
1111
import requests_cache
1212
from xml.sax.saxutils import escape, quoteattr
1313
from lxml import html, etree
14-
from urlparse import urljoin
14+
from urllib.parse import urljoin
1515

1616
requests_cache.install_cache(cache_name='debates', allowable_codes=(200, 404))
1717
BASE_SOURCE_URL = 'https://api.parliament.uk'
@@ -183,9 +183,9 @@ def walk(ol, typ, prefix=''):
183183
title = link.text_content()
184184
url = BASE_SOURCE_URL + link.get('href')
185185
if re.match('ORALL? ANS[WN]?ERS? [Tt][Oo] [OQU]UESTIONS?[.,]?$', title):
186-
next_prefix = u'Oral Answers to Questions &#8212; '
186+
next_prefix = 'Oral Answers to Questions &#8212; '
187187
elif re.match('ORDERS OF THE\.? DAY[.,:]?$', title):
188-
next_prefix = u'Orders of the Day &#8212; '
188+
next_prefix = 'Orders of the Day &#8212; '
189189
else:
190190
next_prefix = ''
191191
out += output_xml('%s-heading' % typ, '%s%s' % (prefix, escape(title)), url)
@@ -225,13 +225,13 @@ for year in range(1919, 1935+1):
225225
if "id='commons'" not in res.content:
226226
continue
227227

228-
print '\r\x1b[K%d' % year, month, day,
228+
print('\r\x1b[K%d' % year, month, day, end=' ')
229229
date = '%d-%02d-%02d' % (year, months.index(month)+1, day)
230230
col = 0
231231

232232
tree = html.fromstring(res.content)
233233
ol = tree.cssselect('h3#commons + ol')[0]
234-
out = u'<publicwhip scrapeversion="a" latest="yes">\n'
234+
out = '<publicwhip scrapeversion="a" latest="yes">\n'
235235
out += walk(ol, 'major')
236236
out += '</publicwhip>\n'
237237

get-historic-person-urls

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ for l in string.ascii_lowercase:
5555
for li in lis:
5656
a = li.find('a')
5757
url = a['href']
58-
print '\r\x1b[K' + url,
58+
print('\r\x1b[K' + url, end=' ')
5959
html = requests.get('https://api.parliament.uk/historic-hansard/people/%s/index.html' % url).text
6060
if html == 'Page not found':
6161
html = requests.get('https://api.parliament.uk/historic-hansard/people/%s' % url).text
@@ -99,10 +99,10 @@ for l in string.ascii_lowercase:
9999
people[name] = [mm for mm in people[name] if mm['id'] != pid]
100100
found = True
101101
if not found:
102-
print '\n', url, presence[pid]['min'], presence[pid]['max'], fr, to
102+
print('\n', url, presence[pid]['min'], presence[pid]['max'], fr, to)
103103
raise Exception
104104
else:
105-
print '\n', matches, url
105+
print('\n', matches, url)
106106
raise Exception
107107

108108
json.dump(data, open(JSON, 'w'), indent=2, sort_keys=True)

london-mayors-questions/questions.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#! /usr/bin/env python
1+
#! /usr/bin/env python3
22

33
import os
44
import logging
@@ -84,7 +84,7 @@ def writeScraperState(state, output_folder):
8484
with open(output_file, 'w') as state_json_file:
8585
logger.debug('Writing state file')
8686
state_json_file.write(json_string)
87-
except TypeError, e:
87+
except TypeError as e:
8888
logger.error('Could not serialise to valid JSON: {}'.format(str(e)))
8989

9090

@@ -234,14 +234,14 @@ def parseQuestionPage(content):
234234

235235
question_title = main_content.h1.text.strip()
236236

237-
logger.debug(u'Question title is {}'.format(question_title))
237+
logger.debug('Question title is {}'.format(question_title))
238238

239239
# Extract who asked it
240240

241241
asked_by_name = main_content.find('div', class_='field--name-field-asked-by').find('div', class_='field__item').text.strip()
242242
asked_by_person = getSpeakerObjectFromName(asked_by_name)
243243

244-
logger.debug(u'Question asked by {}'.format(asked_by_person['name']))
244+
logger.debug('Question asked by {}'.format(asked_by_person['name']))
245245

246246
# Try to extract the actual question
247247

@@ -326,7 +326,7 @@ def parseAnswersFromQuestionPage(page_content):
326326
answered_by_name = answer_article.find('div', class_='field--name-field-answered-by').find('div', class_='field__item').text.strip()
327327
answered_by_person = getSpeakerObjectFromName(answered_by_name)
328328

329-
logger.debug(u'Question answered by {}'.format(answered_by_person['name']))
329+
logger.debug('Question answered by {}'.format(answered_by_person['name']))
330330

331331
answer_paragraphs = []
332332

@@ -410,12 +410,12 @@ def getPersonIDFromName(name):
410410
def getSpeakerObjectFromName(name):
411411
''' Given a name, try to find a speaker ID and return a whole object. '''
412412

413-
name = name.replace(u'\u00a0', ' ')
413+
name = name.replace('\u00a0', ' ')
414414
name = stripPatternsFromName(name)
415415
id = getPersonIDFromName(name)
416416
if not id:
417417
if 'Liz Peace' not in name:
418-
logger.warning(u'Could not match name {} to any assembly member'.format(name))
418+
logger.warning('Could not match name {} to any assembly member'.format(name))
419419
id = 'unknown'
420420

421421
return {
@@ -427,7 +427,7 @@ def getSpeakerObjectFromName(name):
427427
def cleanParagraphText(text):
428428

429429
# Remove non-breaking spaces followed by a space.
430-
text = text.replace(u'\u00a0 ', ' ')
430+
text = text.replace('\u00a0 ', ' ')
431431

432432
# Strip trailing whitespace
433433
text = text.strip()
@@ -618,7 +618,7 @@ def loadMembershipsFromFile(members_file):
618618

619619
if name not in person_ids_by_name:
620620
person_ids_by_name[name] = membership['person_id']
621-
logger.debug(u'Added ID map for for {}'.format(name))
621+
logger.debug('Added ID map for for {}'.format(name))
622622
else:
623623
if person_ids_by_name[name] != membership['person_id']:
624624
raise Exception('Multiple people with name {}'.format(name))

members/parl-old-check-party.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
# fixing (or longer term, fix it automatically).
77

88
import re
9-
import urllib
9+
import urllib.request
1010
import lxml.objectify
1111
import sys
1212

@@ -86,10 +86,10 @@ def __init__(self, lord):
8686
self.type = TYPES.index('Elected Hereditary') # One of the 92
8787

8888
def __str__(self):
89-
return u'%s (%s) - %s' % ( self.longTitle, PARTIES[self.party], self.status )
89+
return '%s (%s) - %s' % ( self.longTitle, PARTIES[self.party], self.status )
9090

9191
# Fetch the current live information
92-
lords = urllib.urlopen('http://data.parliament.uk/resources/members/api/lords/all/').read()
92+
lords = urllib.request.urlopen('http://data.parliament.uk/resources/members/api/lords/all/').read()
9393
lords = [ Lord(lord) for lord in lxml.objectify.fromstring(lords).peer ]
9494

9595
for lord in lords:
@@ -113,5 +113,5 @@ def __str__(self):
113113
if PARTIES[lord.party] == 'UK Independence Party' and lordsList.lords[match]['party'] == 'UKIP': continue
114114
if PARTIES[lord.party] == 'Plaid Cymru' and lordsList.lords[match]['party'] == 'PC': continue
115115
if PARTIES[lord.party] == 'Plaid Cymru' and lordsList.lords[match]['party'] == 'PC': continue
116-
print PARTIES[lord.party], lordsList.lords[match]['party']
116+
print(PARTIES[lord.party], lordsList.lords[match]['party'])
117117

members/wikipedia-commons.py

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#!/usr/bin/env python
1+
#!/usr/bin/env python3
22
# -*- coding: latin-1 -*-
33
# $Id: bbcconv.py,v 1.4 2005/03/25 23:33:35 theyworkforyou Exp $
44

@@ -11,8 +11,7 @@
1111

1212
import datetime
1313
import sys
14-
import urllib
15-
import urlparse
14+
import urllib.parse
1615
import re
1716
# import sets
1817

@@ -49,25 +48,22 @@
4948
cons = cons2
5049
name = name2
5150
url = url2
52-
cons = cons.decode('utf-8')
5351
cons = cons.replace('&amp;', '&')
54-
name = name.decode('utf-8')
5552
try:
5653
(id, canonname, canoncons) = memberList.matchfullnamecons(name, cons, date_parl[year])
57-
except Exception, e:
58-
print >>sys.stderr, e
54+
except Exception as e:
55+
print(e, file=sys.stderr)
5956
if not id:
6057
continue
6158
wikimembers[id] = url
6259

63-
print '''<?xml version="1.0" encoding="ISO-8859-1"?>
64-
<publicwhip>'''
65-
k = wikimembers.keys()
66-
k.sort()
60+
print('''<?xml version="1.0" encoding="ISO-8859-1"?>
61+
<publicwhip>''')
62+
k = sorted(wikimembers)
6763
for id in k:
68-
url = urlparse.urljoin(wiki_index_url, wikimembers[id])
69-
print '<personinfo id="%s" wikipedia_url="%s" />' % (id, url)
70-
print '</publicwhip>'
64+
url = urllib.parse.urljoin(wiki_index_url, wikimembers[id])
65+
print('<personinfo id="%s" wikipedia_url="%s" />' % (id, url))
66+
print('</publicwhip>')
7167

7268
#wikimembers = sets.Set(wikimembers.keys())
7369
#print "len: ", len(wikimembers)

members/wikipedia-lords.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#!/usr/bin/env python
1+
#!/usr/bin/env python3
22

33
# Screen scrape list of links to Lords on Wikipedia, so we can link to the articles.
44

@@ -9,7 +9,7 @@
99

1010
import datetime
1111
import sys
12-
import urlparse
12+
import urllib.parse
1313
import re
1414

1515
sys.path.append("../pyscraper")
@@ -32,19 +32,19 @@
3232
id = None
3333
try:
3434
id = lordsList.GetLordIDfname(name, None, date_today)
35-
except Exception, e:
35+
except Exception as e:
3636
continue
3737

3838
if not id:
3939
continue
4040
wikimembers[id] = url
4141

42-
print '''<?xml version="1.0" encoding="ISO-8859-1"?>
43-
<publicwhip>'''
42+
print('''<?xml version="1.0" encoding="ISO-8859-1"?>
43+
<publicwhip>''')
4444
for id, url in sorted(wikimembers.items()):
45-
url = urlparse.urljoin(wiki_index_url, url)
46-
print '<personinfo id="%s" wikipedia_url="%s" />' % (id, url)
47-
print '</publicwhip>'
45+
url = urllib.parse.urljoin(wiki_index_url, url)
46+
print('<personinfo id="%s" wikipedia_url="%s" />' % (id, url))
47+
print('</publicwhip>')
4848

4949
#print "len: ", len(wikimembers)
5050

members/wikipedia-standingdown.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#!/usr/bin/env python
1+
#!/usr/bin/env python3
22

33
# Screen scrape list of who's standing down in the 2010 general election
44

@@ -7,9 +7,7 @@
77
# certain conditions. However, it comes with ABSOLUTELY NO WARRANTY.
88
# For details see the file LICENSE.html in the top level of the source.
99

10-
import datetime
1110
import sys
12-
import urlparse
1311
import re
1412

1513
sys.path.append("../pyscraper")
@@ -19,15 +17,15 @@
1917

2018
page = open('../rawdata/MPs_standing_down_in_2010').read()
2119

22-
print '''<?xml version="1.0" encoding="ISO-8859-1"?>
23-
<publicwhip>'''
20+
print('''<?xml version="1.0" encoding="ISO-8859-1"?>
21+
<publicwhip>''')
2422
m = re.findall('<li><a href="([^"]*)"[^>]*>([^<]*)</a>', page)
2523
for row in m:
2624
url, name = row
2725
name = name.decode('utf-8')
2826
if name in ('Iris Robinson', 'Ashok Kumar', 'David Taylor'): continue
2927
id, canonname, canoncons = memberList.matchfullnamecons(name, None, today)
3028
pid = memberList.membertoperson(id)
31-
print (' <personinfo id="%s" name="%s" standing_down="1" />' % (pid, name)).encode('iso-8859-1')
32-
print '</publicwhip>'
29+
print((' <personinfo id="%s" name="%s" standing_down="1" />' % (pid, name)).encode('iso-8859-1'))
30+
print('</publicwhip>')
3331

pyscraper/base_resolver.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -67,12 +67,12 @@ def import_people_membership(self, mship, posts, orgs):
6767
return
6868

6969
if mship["id"] in self.membertopersonmap:
70-
raise Exception, "Same member id %s appeared twice" % mship["id"]
70+
raise Exception("Same member id %s appeared twice" % mship["id"])
7171
self.membertopersonmap[mship["id"]] = mship['person_id']
7272
self.persontomembermap.setdefault(mship['person_id'], []).append(mship["id"])
7373

7474
if self.members.get(mship["id"]):
75-
raise Exception, "Repeated identifier %s in members JSON file" % mship["id"]
75+
raise Exception("Repeated identifier %s in members JSON file" % mship["id"])
7676
self.members[mship["id"]] = mship
7777

7878
if 'end_date' not in mship:
@@ -90,14 +90,14 @@ def import_people_membership(self, mship, posts, orgs):
9090
mship_start_date <= mship_end_date and
9191
mship_end_date <= cons['end_date']):
9292
if consid and consid != cons['id']:
93-
raise Exception, "Two constituency ids %s %s overlap with MP %s" % (consid, cons['id'], mship['id'])
93+
raise Exception("Two constituency ids %s %s overlap with MP %s" % (consid, cons['id'], mship['id']))
9494
consid = cons['id']
9595
if not consid:
96-
raise Exception, "Constituency '%s' not found" % mship["constituency"]
96+
raise Exception("Constituency '%s' not found" % mship["constituency"])
9797
# check name in members file is same as default in cons file
9898
backformed_cons = self.considtonamemap[consid]
9999
if backformed_cons != mship["constituency"]:
100-
raise Exception, "Constituency '%s' in members file differs from first constituency '%s' listed in cons file" % (mship["constituency"], backformed_cons)
100+
raise Exception("Constituency '%s' in members file differs from first constituency '%s' listed in cons file" % (mship["constituency"], backformed_cons))
101101

102102
# check first date ranges don't overlap, MPs only
103103
# Only check modern MPs as we might have overlapping data previously
@@ -108,7 +108,7 @@ def import_people_membership(self, mship, posts, orgs):
108108
or cons['start_date'] <= mship['end_date'] <= cons['end_date'] \
109109
or mship['start_date'] <= cons['start_date'] <= mship['end_date'] \
110110
or mship['start_date'] <= cons['end_date'] <= mship['end_date']:
111-
raise Exception, "%s %s Two MP entries for constituency %s with overlapping dates" % (mship, cons, consid)
111+
raise Exception("%s %s Two MP entries for constituency %s with overlapping dates" % (mship, cons, consid))
112112
# then add in
113113
self.considtomembermap.setdefault(consid, []).append(mship)
114114

@@ -124,7 +124,7 @@ def import_people_names(self, person):
124124
if person['id'] not in self.persontomembermap:
125125
return
126126
self.persons[person['id']] = person
127-
memberships = map(lambda x: self.members[x], self.persontomembermap[person['id']])
127+
memberships = [self.members[x] for x in self.persontomembermap[person['id']]]
128128
for other_name in person.get('other_names', []):
129129
if other_name.get('note') == 'Main':
130130
self.import_people_main_name(other_name, memberships)
@@ -213,7 +213,7 @@ def name_on_date(self, person_id, date):
213213
if nm['lordofname']:
214214
name += ' of %s' % nm['lordofname']
215215
return name
216-
raise Exception, 'No found for %s on %s' % (person['id'], date)
216+
raise Exception('No found for %s on %s' % (person['id'], date))
217217

218218
def membertoperson(self, memberid):
219219
return self.membertopersonmap[memberid]

0 commit comments

Comments
 (0)