【发布时间】:2019-08-11 09:44:42
【问题描述】:
Excel 列如下。我想检查 B 列中的内容与 A 列中的那些文本的最大相似度。
A 列有几个用“;”分隔的字符串 B 列只有 1 个字符串
这是我想出的 xlrd 和 xlwt。
import xlwt, xlrd
from difflib import SequenceMatcher
workbook = xlrd.open_workbook("C:\\file.xlsx")
old_sheet = workbook.sheet_by_index(0)
book = xlwt.Workbook(encoding='cp1252', style_compression = 0)
sheet = book.add_sheet('Sheet1', cell_overwrite_ok = True)
for row_index in range(0, old_sheet.nrows):
new_list = []
Cell_a = old_sheet.cell(row_index, 0).value
Cell_b = old_sheet.cell(row_index, 1).value
Cell_a_list = Cell_a.split("; ")
ratio_list = []
for each in Cell_a_list:
ratio = SequenceMatcher(None, each, Cell_b).ratio()
ratio_list.append(ratio)
Cell_c = max(ratio_list)
sheet.write(row_index, 0, Cell_a)
sheet.write(row_index, 1, Cell_b)
sheet.write(row_index, 2, Cell_c)
book.save("C:\\file-1.xls")
除了下图,Pandas 的方式看起来如何?谢谢。
import pandas as pd
data = {'Column_a' : ["Spaghetti, BL; Pasta, without eggs, WKB; Pasta, without eggs, BL; Pasta, with eggs, WKB",
"Noodles, instant, portion pack, WKB; Vermicelli (Angel Hair), BL; Beef, fillet, tenderloin (H2)",
"Beef, center brisket (B2); Beef, center brisket, with bones (B2); Beef, Silverside (F2a); Beef, Sirloin steak (H1)",
"Beef, minced; Beef/pork, minced; Veal, breast (D1), with bones; Veal, schnitzel/escalope (A5)",
"Pork, fillet, tenderloin (B); Pork, schnitzel/escalope (AA)"],
'Column_b' : ["Fresh tortellini or ravioli, WKB",
"Beef, rumpsteak (H3)",
"Beef, shreds or dices (H3, F)",
"Veal, loin (B2)",
"Pork, schnitzel/escalope (A)"]}
df = pd.DataFrame(data)
【问题讨论】:
标签: python pandas similarity