美文网首页
文本比对(不借助任何第三方库)

文本比对(不借助任何第三方库)

作者: 小诸葛686 | 来源:发表于2023-06-20 17:39 被阅读0次

    基于python实现的文本比对,计算出文本相同部分。

    import time
    
    file = open(r"data/s1.txt", "r", encoding="utf-8")
    s1 = file.read()
    
    file = open(r"data/s2.txt", "r", encoding="utf-8")
    s2 = file.read()
    
    
    # 1.将文档1,文档2按单个字符分词。
    # 2.求两个分词集合交集。
    # 3.根据文档1和交集内容计算得到字符串tmp,判断tmp是否存在两个文档。
    # 4.存在继续执行3。
    # 5.不存在则tmp为相同内容。
    # 6.继续执行3直到处理文档结束。
    def by_set():
        set1 = set(s1)
        set2 = set(s2)
        res = set1.intersection(set2)
    
        tmp = ''
        count = 0
        for s in s1:
            tmp_str = (tmp + s).lstrip().lstrip('\n')
            flag = (s in res) and (tmp_str in s1) and (tmp_str in s2)
            if flag:
                tmp += s
            else:
                res_tmp = tmp.replace('\n', '').replace(' ', '')
                if len(res_tmp) > 10:
                    tmp_result = tmp.strip().strip('\n')
                    print(tmp_result)
    
                    print('\n\n\n---------------------------------------------------------------------------------------------\n\n\n')
                tmp = s
    
            count += 1
            if count == len(s1):
                res_tmp = tmp.replace('\n', '').replace(' ', '')
                if len(res_tmp) > 12:
                    tmp_result = tmp.strip().strip('\n')
                    print(tmp_result)
    
    
    start = time.time()
    by_set()
    end = time.time()
    
    print('\n\n\n')
    print(end - start)
    
    

    相关文章

      网友评论

          本文标题:文本比对(不借助任何第三方库)

          本文链接:https://www.haomeiwen.com/subject/qwayydtx.html