【问题标题】:How to check if strings in two list are almost equal using python如何使用python检查两个列表中的字符串是否几乎相等
【发布时间】:2021-03-30 23:10:14
【问题描述】:

我正在尝试在两个列表中找到几乎匹配的字符串。假设有如下两个列表

string_list_1 = ['apple_from_2018','samsung_from_2017','htc_from_2015','nokia_from_2010','moto_from_2019','lenovo_decommision_2017']

string_list_2 =
['apple_from_2020','samsung_from_2021','htc_from_2015','lenovo_decommision_2017']

Output
Similar = ['apple_from_2018','samsung_from_2017','htc_from_2015','lenovo_decommision_2017']
Not Similar =['nokia_from_2010','moto_from_2019']

我使用下面的实现尝试了上面的一个,但它没有给出正确的结果

similar = []
not_similar = []
for item1 in string_list_1:
   for item2 in string_list_2:
      if SequenceMatcher(a=item1,b=item2).ratio() > 0.90:
         similar.append(item1)
      else:
          not_similar.append(item1)
  

当我尝试上述实现时,它并不像预期的那样。如果有人可以识别缺失的部分并获得所需的结果,将不胜感激

【问题讨论】:

  • 你想找出两个字符串列表之间的相似词和不同词吗?
  • @TanishqVyas 是的,我需要几乎相似的字符串应该有 90% 匹配
  • 以上代码工作正常,因为它们中的大多数不匹配 90% 匹配
  • 你想在匹配的时候排除部分年份,那么它是可能的。
  • 这能回答你的问题吗? How to find list intersection?

标签: python-3.x list list-comparison


【解决方案1】:

您可以使用以下函数来查找两个给定字符串之间的相似性

from difflib import SequenceMatcher

def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()


print(similar("apple_from_2018", "apple_from_2020"))

输出:

0.8666666666666667

因此使用此功能,您可以选择超过百分比相似度阈值的字符串。尽管您可能需要将阈值从 90 降低到 85 才能获得预期的输出。

因此,以下代码应该适合您

string_list_1 = ['apple_from_2018','samsung_from_2017','htc_from_2015','nokia_from_2010','moto_from_2019','lenovo_decommision_2017']

string_list_2 = ['apple_from_2020','samsung_from_2021','htc_from_2015','lenovo_decommision_2017']



from difflib import SequenceMatcher


similar = []
not_similar = []
for item1 in string_list_1:

    # Set the state as false
    found = False
    for item2 in string_list_2:
        if SequenceMatcher(None, a=item1,b=item2).ratio() > 0.80:
            similar.append(item1)
            found = True
            break
    
    if not found:
        not_similar.append(item1)

print("Similar : ", similar)
print("Not Similar : ", not_similar)

输出:

Similar :  ['apple_from_2018', 'samsung_from_2017', 'htc_from_2015', 'lenovo_decommision_2017']
Not Similar :  ['nokia_from_2010', 'moto_from_2019']

这确实减少了时间和多余的追加。此外,由于 90 太高,我已将相似性度量降低到 80。但请随意调整这些值。

【讨论】:

  • 请问是否可以使用更好的编码格式避免嵌套循环
  • 澄清一下,您希望从字符串 list1 中选择所有字符串,以便它们与列表 2 中的任何一个字符串匹配 90% 或更多,这种解释是否正确?
  • 是的,Tanisha。但是有没有可能改进编码格式
  • 您必须使用嵌套循环,因为您必须检查所有可能满足您条件的对。因此,您必须遍历所有这些。但是,一旦找到匹配的元素,您可以使用 continue 关键字切换到下一个循环。此外,如果相似度小于 0.9,您上面列出的代码还会多次迭代地附加不匹配的单词。因此,您必须确保适当地中断循环以减少花费的时间并改进解决方案。但是嵌套是强制性的。这是 Tanishq* :)
猜你喜欢
  • 2018-06-07
  • 1970-01-01
  • 2015-10-17
  • 2015-10-30
  • 1970-01-01
  • 2020-11-09
  • 1970-01-01
  • 1970-01-01
  • 2021-01-12
相关资源
最近更新 更多