This module provides functions for extraction currency information fro

  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
"""
This module provides functions for extraction currency information
from dbpedia.
"""
import simplejson
import logging
import re
from settings import settings
from lib.models import session, Country, SA, Currency
import util
def do_query():
"""
Fetch currency information for all countries from dbpedia.
"""
query = """
SELECT * WHERE {
{
?cc dbpedia2:currencyCode ?cur1_code.
OPTIONAL {
?cur1 dbpedia2:isoCode ?cur1_code.
?cur1 foaf:page ?cur1_wiki_en.
OPTIONAL {
?cur1 dbpedia2:wikipage-ru ?cur1_wiki_ru.
}
?cur1 rdfs:label ?cur1_label.
FILTER ( lang(?cur1_label) = 'ru' || lang(?cur1_label) = 'en' )
}
OPTIONAL {
?cc dbpedia2:cctld ?cc_tld.
?cc_tld rdfs:label ?cc_tld_label.
FILTER ( lang(?cc_tld_label) = 'en' )
}
}
UNION {
?cc dbpedia2:currency ?cur2.
?cur2 foaf:page ?cur2_wiki_en.
OPTIONAL {
?cur2 dbpedia2:wikipage-ru ?cur2_wiki_ru.
}
?cur2 rdfs:label ?cur2_label.
?cur2 dbpedia2:isoCode ?cur2_code.
FILTER ( lang(?cur2_label) = 'ru' || lang(?cur2_label) = 'en' )
OPTIONAL {
?cc dbpedia2:cctld ?cc_tld.
?cc_tld rdfs:label ?cc_tld_label.
FILTER ( lang(?cc_tld_label) = 'en' )
}
}
}
order by ?cc
"""
return util.sparql_query_all(query, debug=False)
def normalize_code(code):
"""
Try to extract valid currency code from dbpedia trash.
"""
#if 'EUR' in code:
# code = 'EUR'
#elif '(' in code:
# code = code[:code.index('(')].strip()
#elif ',' in code:
# code = code[:code.index(',')].strip()
re_code = re.compile(r'([a-z]+)', re.I)
match = re_code.search(code)
if match:
return match.group(1).upper()
else:
return None
def normalize_label(label):
"""
Delete some noise from dbpedia currency label.
"""
label = label.rstrip(u'"').strip()
return label
def parse_response(rows):
"""
Normalize dbpedia response.
"""
curs = {}
for row in rows:
cc_uri = util.wikipedia_uri(row['cc']['value'])
if 'cc_tld_label' in row:
cc_tld = row['cc_tld_label']['value'].lstrip('.')
else:
cc_tld = None
tries = []
if 'cur1_code' in row:
code = row['cur1_code']['value']
code = normalize_code(code)
if 'cur1_wiki_en' in row:
wiki_en = row['cur1_wiki_en']['value']
else:
wiki_en = None
if 'cur1_wiki_ru' in row:
wiki_ru = row['cur1_wiki_ru']['value']
else:
wiki_ru = None
if 'cur1_label' in row:
lang = row['cur1_label']['xml:lang']
label = normalize_label(row['cur1_label']['value'])
else:
lang = 'en'
label = code
tries.append((lang, label, code, wiki_en, wiki_ru, True))
if 'cur2' in row:
code = row['cur2_code']['value']
code = normalize_code(code)
lang = row['cur2_label']['xml:lang']
label = normalize_label(row['cur2_label']['value'])
if 'cur1_wiki_en' in row:
wiki_en = row['cur1_wiki_en']['value']
else:
wiki_en = None
if 'cur1_wiki_ru' in row:
wiki_ru = row['cur1_wiki_ru']['value']
else:
wiki_ru = None
tries.append((lang, label, code, wiki_en, wiki_ru, False))
for lang, label, code, wiki_en, wiki_ru, main in tries:
if not cc_uri in curs:
curs[cc_uri] = {}
if not code in curs[cc_uri]:
curs[cc_uri][code] = {'code': code, 'labels': {lang: label},
'tld': cc_tld, 'uri': cc_uri,
'wiki_en': wiki_en, 'wiki_ru': wiki_ru,
'main': main,}
else:
if not lang in curs[cc_uri][code]['labels']:
curs[cc_uri][code]['labels'][lang] = label
if wiki_en and not curs[cc_uri][code]['wiki_en']:
curs[cc_uri][code]['wiki_en'] = wiki_en
if wiki_ru and not curs[cc_uri][code]['wiki_ru']:
curs[cc_uri][code]['wiki_ru'] = wiki_ru
return curs
def update():
"""
Update database with currencies which was parsed from dbpedia.
"""
items = parse_response(do_query())
found = 0
notfound = 0
for curs in items.itervalues():
cur1 = curs.values()[0]
cc_uri = cur1['uri']
cc_tld = cur1['tld']
try:
db_country = session.query(Country).filter(
(Country.wikipedia_en == cc_uri) |
(Country.id == cc_tld)).one()
except SA.exceptions.InvalidRequestError, ex:
logging.debug('No country with %s uri or %s code' % (cc_uri, cc_tld))
notfound += 1
else:
found += 1
cur = None
if len(curs) == 1:
cur = curs.values()[0]
else:
for itercur in curs.itervalues():
if itercur['main']:
cur = itercur
break
if cur is None:
cur = curs.values()[0]
logging.debug('Processing %s [%s]: %s' % (db_country, cc_tld, cur['code']))
try:
curobj = session.query(Currency).filter(
Currency.id == cur['code']).one()
except SA.exceptions.InvalidRequestError, ex:
curobj = Currency()
curobj.id = cur['code']
curobj.title_en = cur['labels']['en']
curobj.title_ru = cur['labels'].get('ru')
curobj.wikipedia_en = cur['wiki_en']
curobj.wikipedia_ru = cur['wiki_ru']
session.save(curobj)
logging.debug('Found new currency: %s, wiki_en: %s, wiki_ru: %s' % (curobj.id, curobj.wikipedia_en, curobj.wikipedia_ru))
db_country.currency = curobj.id
session.commit()
logging.debug('Valid: %d, invalid: %d' % (found, notfound))
number = session.query(Country).filter(Country.currency == None).count()
logging.debug('There are %d countries without currency in DB' % number)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
update()