PYTHON处理字符串匹配

今天遇见一个问题:要进行字符串匹配。
实际业务:比较N个JSON串和一行文本的相似度。并选择最像的M个JSON。

业务逻辑和这个一致:
我这里有100个数字
在这里插入图片描述然后另外一个表格在这里插入图片描述请找出表格1和表格2相同的数据、相似度并定位。
(丢几个数据不重要,重要的是相似度)
我XX日了狗了。

————————————————————————

写个脚本定位下:

def get_list2(data, line=2):
    data = data.replace('\n', '')
    data = str(data)
    data_list =[]
    if data == '':
        data ='¥¥'
    for i in range(0, int(len(data)/line)):
        part = data[i*line:i*line+line]
        data_list.append(part)
    return data_list




file1 = open('l1.txt', 'r', encoding='gbk')
file2 = open('l2.txt', 'r', encoding='gbk',errors='replace')
data1 = file1.read()
data2 = file2.read()
file1.close()
file2.close()
count = []
key_list = []
list1 = data1.split("/>")
list2 = get_list2(data2)

# print(list1)
# print(list2)
for part in list1:
    count_num = 0
    key_part = []
    for key in list2:
        if part.find(key) != -1:
            count_num = count_num+1
            key_part.append(key)
    key_part_all = "".join(key_part)
    count.append(count_num)
    key_list.append(key_part_all)
print(len(count))
print(len(list1))
for i in range(len(count)):
    for j in range(len(count)-i-1):
        if count[j] < count[j+1]:
            count[j], count[j+1] = count[j+1], count[j]
            list1[j], list1[j+1] = list1[j+1], list1[j]
            key_list[j], key_list[j+1] = key_list[j+1], key_list[j]
print(list1[0])
print('**************************************************************************')
print(list1[1])
print('--------------------------------------------------------------------------')
print("最符合的信息串为:{}\n匹配的正文为{}\n匹配权重为{}".format(list1[0], key_list[0], count[0]))
print('\n*******************\n')
print("比较符合的信息串为:{}\n匹配的正文为{}\n匹配权重为{}".format(list1[1], key_list[1], count[0]))

第一:把JSON等保存为Dbunit。(让他们丢失格式,可以分开)
然后把字符串拼接到l1.txt。
然后需要匹配的字符串为l2.txt。
然后将要匹配的字符串给拆解成各种2、3个的小字符串,然后和各个列表进行比较。

写完发现:虽然业务逻辑各种简陋,但是挺管用的。

凑合着用吧。



优化了一丢丢算法:

import time
import sys
file1_root = r'F:\d1\getmessage\l1.txt'
file2_root = r'F:\d1\getmessage\l2.txt'


def get_char(end='end', end_char=''):
    data = 'char_is_null'
    while 1:
        var = input()
        if var == str(end):
            break
        elif end_char != '' and var.find(end_char) != -1:
            var = var[0:var.find(end_char)]
            data = '{}\n{}'.format(data, var)
            break
        else:
            data = '{}\n{}'.format(data, var)
    return data.replace('char_is_null\n', '')


def get_list2(data, line=2):
    data = data.replace('\n', '')
    data = str(data)
    data_list =[]
    if data == '':
        data = '**************************'
    for i in range(0, int(len(data)/line)):
        part = data[i*line:i*line+line]
        data_list.append(part)
    return data_list


file1 = open(file1_root, 'a+', encoding='gbk', errors='replace')
file1.close()
file2 = open(file2_root, 'a+', encoding='gbk', errors='replace')
file2.close()
while 1:
    file1 = open(file1_root, 'r', encoding='gbk', errors='replace')
    file2 = open(file2_root, 'r', encoding='gbk', errors='replace')
    data1 = file1.read()
    data2 = file2.read()
    print("获取的字符串为:{}".format(data1))
    print("比对的字符串为:{}".format(data2))
    file1.close()
    file2.close()
    get_data = input("需要获取文件?Y/N\n")
    if get_data == 'Y' or get_data == 'y':
        print("以/>分隔的字符串,以end结束\n")
        data1 = get_char()
        data2 = input("比对的字符串为,以end结束:\n")
        data2 = get_char()
        file1 = open(file1_root, 'w+', encoding='gbk', errors='replace')
        file1.write(data1)
        file1.close()
        file2 = open(file2_root, 'w+', encoding='gbk', errors='replace')
        file2.write(data2)
        file2.close()
    else:
        print('不获取新数据,处理历史数据\n')
    data1 = data1.lower()
    data2 = data2.lower()
    count = []
    key_list = []
    list1 = data1.split("/>")
    list1.append('')
    list2 = get_list2(data2)
    try:
        # print(list1)
        # print(list2)
        for part in list1:
            count_num = 0
            key_part = []
            for key in list2:
                if part.find(key) != -1:
                    count_num = count_num + 1
                    key_part.append(key)
            key_part_all = "".join(key_part)
            count.append(count_num)
            key_list.append(key_part_all)
        print(len(count))
        print(len(list1))
        for i in range(len(count)):
            for j in range(len(count) - i - 1):
                if count[j] < count[j + 1]:
                    count[j], count[j + 1] = count[j + 1], count[j]
                    list1[j], list1[j + 1] = list1[j + 1], list1[j]
        for i in range(100):
            if count[i] <= count[0] * 0.5 and i > 0:
                break
            else:
                print(list1[0])
                print('**************************************************************************')
                print('--------------------------------------------------------------------------')
                print("符合的信息串为:{}\n匹配的正文为{}\n匹配权重为{}".format(list1[0], key_list[0], count[0]))
    except Exception as e:
        print(e)
    var = input('点击重新操作?Y/N')
    if var == 'Y' or var == 'y':
        pass
    else:
        break





  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python字符串匹配有多种方法,其中包括KMP算法和正则表达式等。KMP算法是一种高效的字符串匹配算法,可以速找到目标字符串在源字符串中的位置。 此外,Python还提供了强大的正则表达式功能,可以用来进行复杂的字符串匹配和替换操作。 对于字符串匹配问题,Python提供了丰富的内置函数和方法,如find()、index()、startswith()、endswith()等,可以根据具体需求选择合适的方法来进行字符串匹配。如果需要对大量的字符串进行匹配操作,可以考虑使用字符串匹配算法和正则表达式来提高效率。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Python字符串匹配算法KMP实例](https://download.csdn.net/download/weixin_38550812/12876336)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Python字符串匹配之6种方法的使用详解](https://download.csdn.net/download/weixin_38630463/12863629)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [xml文件批量处理python脚本](https://download.csdn.net/download/caoxinri123/88239057)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值