这里是一个快速的尝试:
import requests
import bs4 # the 'beautifulsoup4' module
import pickle
# find an 'all the countries' listing
url = "http://www.nationsonline.org/oneworld/countries_of_the_world.htm"
r = requests.get(url)
bs = bs4.BeautifulSoup(r.text)
# grab all table rows
rows = [
[cell.text.strip() for cell in row.findAll('td')]
for row in bs.findAll('tr')
]
# filter for just the rows containing country-name data
rows = [row[1:] for row in rows if len(row) == 4]
# create a look-up table
country = {}
for en,fr,lo in rows:
country[en] = en
country[fr] = en
country[lo] = en
# and store it for later use
with open('country.dat', 'wb') as outf:
pickle.dump(country, outf)
我们现在有一个字典,它采用各种国家拼写并返回每个国家的规范英文名称。根据您的数据,您可能希望将其扩展为包括 ISO 国家/地区缩写等。
对于字典中没有的拼写,我们可以搜索相近的替代:
import difflib
def possible_countries(c):
res = difflib.get_close_matches(c, country.keys(), cutoff=0.5)
return sorted(set(country[r] for r in res))
我们可以使用它来处理您的 .csv 文件,提示进行适当的替换:
import sys
import pickle
import csv
def main(csvfname):
# get existing country data
with open('country.dat', 'rb') as inf:
country = pickle.load(inf)
# get unique country names from your csv file
with open(csvfname, 'rb') as inf:
data = sorted(set(row[0] for row in csv.reader(inf)))
for c in data:
if c not in country:
print('"{}" not found'.format(c))
sugg = possible_countries(c)
if sugg:
print('Suggested replacements:\n {}'.format('\n '.join(sugg)))
else:
print('(no suggestions)')
repl = raw_input('Enter replacement value (or <Enter> for none): ').strip()
if repl:
country[c] = repl
# re-save country data
with open('country.dat', 'wb') as outf:
pickle.dump(country, outf)
if __name__=="__main__":
if len(sys.argv) == 2:
main(sys.argv[1])
else:
print('Usage: python fix_countries.py csvfname')