2012-08-11 70 views
-3

python的新功能,請和我一起裸照。我正在比較(國名拼寫)兩個csv文件的值並打印沒有匹配的國家/地區的名稱。我正在對兩個具有國名的數據集進行空間分析,並且我收到的結果不準確,我認爲這是由國名拼寫錯誤造成的。我提取國名並將它們保存到兩個不同的CSV文件中進行比較。我查看了本網站上的其他幾個示例(許多人希望比較幾個列並執行各種其他功能),並且未能成功操作代碼。使用Python比較CSV文件和打印結果

+3

如果您可以提供一些有代表性的輸入數據樣本(以及所需的輸出),這將會很有幫助。 – Levon 2012-08-11 14:51:20

+0

輸入數據很簡單。這兩個CVS文件都有一列(國名)。數據已從空間數據集(shapefile)中提取並保存到CSV文件以比較差異。我的空間分析是產生不準確的結果,我認爲這是由於名稱拼寫的微小差異造成的。因此,希望找出沒有匹配的國家名稱。 – dchaboya 2012-08-11 14:59:17

+0

@dchaboya,你最好在添加其他信息時更新最初的問題身體 – 2012-08-11 15:07:22

回答

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) 

我們現在有一個字典,這需要各種國家的拼寫和每個返回規範的英文名稱。根據你的數據,你可能希望延長這包括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') 
+0

這太棒了。感謝您花時間回覆! – dchaboya 2012-08-24 17:57:34

1

如果我理解正確的話,你可以使用

diff -u file1 file2 

或任何其他文件比較工具。 如果不是,請指定關於輸入文件的更多細節。