【问题标题】:Compare CSV files and print results using Python使用 Python 比较 CSV 文件并打印结果
【发布时间】:2012-08-11 14:49:10
【问题描述】:

我希望比较(国家名称的拼写)两个 csv 文件的值并打印不匹配的国家/地区的名称。我正在对两个具有国名的数据集进行空间分析,我收到的结果不准确,我认为这是由于国名拼写错误造成的。我提取了国家名称并将它们保存到两个不同的 CSV 文件中进行比较。我查看了该站点上的其他几个示例(许多希望比较几列并执行各种其他功能),但未能成功操作代码。

【问题讨论】:

  • 如果您能提供一些输入数据(和所需输出)的代表性样本,将会很有帮助。
  • 输入数据很简单。两个 CVS 文件都有一列(国家名称)。数据已从空间数据集(shapefile)中提取并保存到 CSV 文件以比较差异。我的空间分析产生了不准确的结果,我认为这是由于名称拼写的微小差异造成的。因此,希望找出不匹配的国家/地区名称。
  • @dchaboya,添加附加信息时最好更新初始问题正文
  • 你试图识别什么 - 例如,“Kenya”是“Kenyah” - 或者我可以编造各种其他的 - 匹配有多接近,你是否使用 ISO 代码等等...这样一旦数据标准化?

标签: python csv compare


【解决方案1】:

这里是一个快速的尝试:

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')

【讨论】:

  • 这太棒了。感谢您抽出宝贵时间回复!
【解决方案2】:

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

diff -u file1 file2

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-24
    • 2015-01-20
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 2014-05-25
    • 2022-11-15
    • 1970-01-01
    相关资源
    最近更新 更多