任务:获取两个文本文件并输出 100% 匹配和 75% 匹配。
解决方案:
import difflib
import csv
# Imports and parses the files
fileA = open("H:/comm.names.txt", 'r')
try:
setA = fileA.readlines()
finally:
fileA.close()
fileB = open("H:/acad.names.txt", 'r')
try:
setB = fileB.readlines()
finally:
fileB.close()
# 100% Match
setMatch100 = set(setA).intersection(setB)
Match100 = open("H:\Match100.txt", 'w')
try:
for item in setMatch100:
Match100.write(item)
finally:
Match100.close()
# Remove 100% matches from the two lists
setA_LeftOver = set(setA).difference(setMatch100)
setB_LeftOver = set(setB).difference(setMatch100)
#Return the best match for setA_LeftOver[i] in setB_LeftOver that is at least 75% matching.
fMatch75 = open("H:\Match75.csv", 'w')
Match75 = csv.writer(fMatch75)
try:
Match75.writerow(['File A', 'File B'])
for item in setA_LeftOver:
match = difflib.get_close_matches(item, setB_LeftOver, 1, 0.75)
if len(match) > 0:
row = [item.rstrip(), match[0].rstrip()]
Match75.writerow(row)
finally:
fMatch75.close()
问题:这行得通,但是结果不是很好。下面是一个匹配的例子:
Fovea Pharmaceuticals SA 神户制药大学我不能将 Diff 中的最低百分比提高太多,因为我需要能够将 Univ 与 University 相匹配。另外,我不能只确保第一个单词匹配,因为某些字符串以“The”开头,并且需要与排除“The”的字符串匹配。任何人都可以指出我的方向,它会抛出技术上 75% 相似但对人类根本不相似的匹配吗?