python replace函数模糊替换_Python模糊搜索和替换

I need to perfom fuzzy search for sub-string in string and replace that part. For example:

str_a = "Alabama"

str_b = "REPLACED"

orig_str = "Flabama is a state located in the southeastern region of the United States."

print(fuzzy_replace(str_a, str_b, orig_str)) # fuzzy_replace code should be implemented

# Output: REPLACED is a state located in the southeastern region of the United States.

The search itself is simple with fuzzywuzzy module, but it gives me only ratio of difference between strings. Are there any ways to find a position in original string where sub-string fuzzy matches to?

解决方案

Try this..

from fuzzywuzzy import fuzz

def fuzzy_replace(str_a, str_b, orig_str):

l = len(str_a.split()) # Length to read orig_str chunk by chunk

splitted = orig_str.split()

for i in range(len(splitted)-l+1):

test = " ".join(splitted[i:i+l])

if fuzz.ratio(str_a, test) > 75: #Using fuzzwuzzy library to test ratio

before = " ".join(splitted[:i])

after = " ".join(splitted[i+1:])

return before+" "+str_b+" "+after #Output will be sandwich of these three strings

str_a = "Alabama is a"

str_b = "REPLACED"

orig_str = "Flabama is a state located in the southeastern region of the United States."

print fuzzy_replace(str_a, str_b, orig_str)

This prints

REPLACED state located in the southeastern region of the United States.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值