使用Python比较CSV文件和打印结果

时间:2012-08-11 14:49:11

标签: python csv compare

我希望比较(国家/地区名称的拼写)两个csv文件的值,并打印不匹配的国家/地区的名称。我正在对两个有国名的数据集进行空间分析,而且我收到的结果不准确,我认为这是因为国名的拼写错误。我提取了国家/地区名称并将其保存到两个不同的CSV文件中进行比较。我已经看过这个网站上的其他几个例子(许多人希望比较几个列并执行各种其他功能)并且还没有成功地操作代码。

2 个答案:

答案 0 :(得分:3)

以下是对此的快速抨击:

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)

我们现在有一个dict,它采用各种国家拼写,并返回每个拼写的规范英文名称。根据您的数据,您可能希望将其扩展为包括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')

答案 1 :(得分:1)

如果我理解正确,你可以使用

diff -u file1 file2

或任何其他文件比较工具。 如果没有 - 请指定有关输入文件的更多详细信息。