網(wǎng)站首頁 編程語言 正文
場景:
1.計算SimHash值,及Hamming距離。
2.SimHash適用于較長文本(大于三五百字)的相似性比較,文本越短誤判率越高。
Python實現(xiàn):
代碼如下
# -*- encoding:utf-8 -*- import math import jieba import jieba.analyse class SimHash(object): def getBinStr(self, source): if source == "": return 0 else: x = ord(source[0]) << 7 m = 1000003 mask = 2 ** 128 - 1 for c in source: x = ((x * m) ^ ord(c)) & mask x ^= len(source) if x == -1: x = -2 x = bin(x).replace('0b', '').zfill(64)[-64:] return str(x) def getWeight(self, source): return ord(source) def unwrap_weight(self, arr): ret = "" for item in arr: tmp = 0 if int(item) > 0: tmp = 1 ret += str(tmp) return ret def sim_hash(self, rawstr): seg = jieba.cut(rawstr) keywords = jieba.analyse.extract_tags("|".join(seg), topK=100, withWeight=True) ret = [] for keyword, weight in keywords: binstr = self.getBinStr(keyword) keylist = [] for c in binstr: weight = math.ceil(weight) if c == "1": keylist.append(int(weight)) else: keylist.append(-int(weight)) ret.append(keylist) # 降維 rows = len(ret) cols = len(ret[0]) result = [] for i in range(cols): tmp = 0 for j in range(rows): tmp += int(ret[j][i]) if tmp > 0: tmp = "1" elif tmp <= 0: tmp = "0" result.append(tmp) return "".join(result) def distince(self, hashstr1, hashstr2): length = 0 for index, char in enumerate(hashstr1): if char == hashstr2[index]: continue else: length += 1 return length if __name__ == "__main__": simhash = SimHash() str1 = '咱哥倆誰跟誰啊' str2 = '咱們倆誰跟誰啊' hash1 = simhash.sim_hash(str1) print(hash1) hash2 = simhash.sim_hash(str2) distince = simhash.distince(hash1, hash2) value = 5 print("simhash", distince, "距離:", value, "是否相似:", distince<=value)
原文鏈接:https://coderl.blog.csdn.net/article/details/122740744
相關(guān)推薦
- 2023-12-25 前后端驗證碼分析(字母&計算)
- 2022-06-13 Flutter實現(xiàn)自定義搜索框AppBar的示例代碼_Android
- 2021-11-30 Linux?Autofs自動掛載服務(wù)安裝部署教程_Linux
- 2022-08-03 C#中POST接口formdata傳參模板的記錄_C#教程
- 2022-08-25 Python面向?qū)ο蟮娜筇匦苑庋b、繼承、多態(tài)_python
- 2022-04-02 詳解python中的IO操作方法_python
- 2022-07-26 Golang異常處理之defer,panic,recover的使用詳解_Golang
- 2023-07-08 keycloak更新token調(diào)用updateToken函數(shù)無效,解決辦法
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支