微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将字符串与键进行比较,并在字符串模糊匹配后返回值

如何解决将字符串与键进行比较,并在字符串模糊匹配后返回值

我有一个200000家公司的字典。我正在使用前两个单词作为键。 例如:

{'Dell international' : ['Dell international services']}
  1. 我正在按行读取一组文本文件,并检查行中是否存在密钥
  2. 如果行中存在键,则将值与行模糊匹配
  3. 如果分数> = 90%,则返回该值并中断循环并移至下一个文件

示例:

if my text file has a line,'Dell International Services Pvt Ltd'. 
I am matching the prevIoUs line with the key,i.e 'Dell international'
Then fuzzy matching the string ('Dell International Services Pvt Ltd') with the value in the dict ('Dell international services') 
if the score is greater than 90% return the value,exiting from the loop and looking in the next file.

到目前为止我所做的:

from fuzzywuzzy import fuzz
from fuzzywuzzy import process

for file in os.listdir(prs_path}:
    with open(prs_path + file) as fd:
            for line in fd:
                line = str(line.lower()).strip()
                for key,value in dict.items():
                    value = eval(str(value).lstrip('[').rstrip(']'))
                    if key in line:
                       score = fuzz.UWratio(line,value)
                       if score >= 90:
                          print(value)
                          continue

它正在返回值,但在第一次匹配后我无法中断循环,因为它正在将行与其他200000键进行比较,并花费很长时间执行。

在第一次比赛后如何停止它并移至下一个文件

解决方法

您可以将匹配项移至函数中,然后从中返回

from rapidfuzz import fuzz

def file_match(file_name,comp_dict):
  with open(file_name) as fd:
    for line in fd:
      line = line.lower().strip()
      for key,value in comp_dict.items():
        value = value[0].lower().strip()
        if key in line:
          if fuzz.WRatio(line,value,processor=None,score_cutoff=90):
            return value

for file in os.listdir(prs_path}:
  value = file_match(prs_path + file,comp_dict)
  if value:
    print(value)

这将应用以下更改:

  1. 将内部循环移动到一个函数,以便可以从中返回,因为如您所述,continue仅会影响当前循环

  2. 直接访问列表中的第一个元素。 为此使用eval速度很慢,而根本不是为了进行eval。

  3. 将dict重命名为comp_dict,因为dict是python使用的关键字,不应被隐藏。

  4. RapidFuzz代替FuzzyWuzzy的用法,因为它更快(它只有fuzz.WRatio,但是取消链接FuzzyWuzzy RapidFuzz始终与unicode一起使用,因此也是如此)。直接将score_cutoff传递给WRatio有助于在无法达到分数时提早退出。由于您已经预先对字符串进行了预处理(小写+条带化),因此不必在WRatio中再次进行此操作,因此可以将其停用。

  5. 您可以使用line.lower().strip()代替str(line.lower()).strip(),因为line.lower()已经返回了字符串。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。