如何循环浏览一个列表,并显示另一文本中每个元素最匹配的结果。当前有两个列表:
const control_name = targetcontrols_array[i];
const source = targetsource_array[i];
目前我可以得到一个单词的结果
Items_1 = ['Apple', 'Red Apple', 'Green Apple', 'Orange 1ltr', 'Orange 5ml', 'Grapes', 'Grapes 500ml', 'Grapes 1lt']
Items_2 = ['Apple', 'Orange', 'Grapes']
我尝试了以下代码,但似乎不起作用
difflib.get_close_matches('Apple', Items_1)
['Apple', 'Red Apple', 'Green Apple']
我希望Items_2中的每个单词都显示如下结果
for i in Items_2
print(difflib.get_close_matches(Item_1[i], Items_2))
答案 0 :(得分:0)
import difflib
Items_1 = ['Apple', 'Red Apple', 'Green Apple', 'Orange 1ltr', 'Orange 5ml', 'Grapes', 'Grapes 500ml', 'Grapes 1lt']
Items_2 = ['Apple', 'Orange', 'Grapes']
print("%-8s %s" % ("Items_2", "Items_1"))
for item in Items_2:
print("%-8s %s" % (item, ", ".join("'%s'" % x for x in difflib.get_close_matches(item, Items_1))))
输出:
Items_2 Items_1
Apple 'Apple', 'Red Apple', 'Green Apple'
Orange 'Orange 5ml', 'Orange 1ltr'
Grapes 'Grapes', 'Grapes 1lt', 'Grapes 500ml'
答案 1 :(得分:0)
如果您希望打印效果很好,可以使用PrettyTable:
from prettytable import PrettyTable
pt = PrettyTable()
pt.field_names = ['Item_2', 'Item_1']
for item in Items_2:
pt.add_row([item, close_match(item, Items_1)])
close_match
可能是您使用的匹配函数(difflib.get_close_matches
)或其他任何函数。
print(pt)
的输出:
+--------+------------------------------------------+
| Item_2 | Item_1 |
+--------+------------------------------------------+
| Apple | ['Apple', 'Red Apple', 'Green Apple'] |
| Orange | ['Orange 1ltr', 'Orange 5ml'] |
| Grapes | ['Grapes', 'Grapes 500ml', 'Grapes 1lt'] |
+--------+------------------------------------------+