使用word2vec的model.wv.most_similar来获取关联性词汇,完整代码如下:
#!/usr/local/python3/bin/python3
# -*- coding: utf-8 -*
import jieba
from gensim.models import word2vec
import logging
#分词
f1 =open("/data/wwwroot/default/asset/fenci.txt",encoding = 'utf-8')
f2 =open("fenci_result.txt", 'a',encoding = 'utf-8')
lines =f1.readlines() # 读取全部内容
for line in lines:
line.replace('\t', '').replace('\n', '').replace(' ','')
seg_list = jieba.cut(line, cut_all=False)
f2.write(" ".join(seg_list))
f1.close()
f2.close()
# 主程序
logging.basicConfig(format='%(asctime)s:%(levelname)s: %(message)s', level=logging.INFO)
sentences =word2vec.Text8Corpus(u"fenci_result.txt") # 加载语料
model =word2vec.Word2Vec(sentences) #训练skip-gram模型,默认window=5
# 计算两个词的相似度/相关程度
try:
y1 = model.wv.similarity(u"中方", u"中国")
except KeyError:
y1 = 0
print(u"【中方】和【中国】的相似度为:", y1)
print("-----\n")
#
# 计算某个词的相关词列表
y2 = model.wv.most_similar(u"威胁", topn=20) # 20个最相关的
print(u"和【威胁】最相关的词有:\n")
for item in y2:
print(item[0], item[1])
print("-----\n")
# 寻找对应关系
print( u"中国-北约,威胁-")
print("-----\n")
y3 =model.wv.most_similar([u'中国', u'北约'], [u'威胁'], topn=3)
for item in y3:
print(item[0], item[1])
print("----\n")
# 寻找不合群的词
y4 =model.wv.doesnt_match(u"放弃 意识".split())
print(u"不合群的词:", y4)
print("-----\n")
model.wv.save_word2vec_format('word2vec.bin')
# 保存模型,以便重用
# model.save(u"word2vec.model",)
# 对应的加载方式
# model_2 =word2vec.Word2Vec.load("text8.model")
# 以一种c语言可以解析的形式存储词向量
#model.save_word2vec_format(u"书评.model.bin", binary=True)
# 对应的加载方式
# model_3 =word2vec.Word2Vec.load_word2vec_format("text8.model.bin",binary=True)
网友回复
有没有不依赖embedding向量的RAG技术?
有没有支持实时打断语音通话并后台帮你执行任何的ai模型?
开源ai大模型文件格式GGUF、MLX、Safetensors、 ONNX 有什么区别?
出海挣钱支付收款PayPal、Wise 、PingPong、Stripe如何选择?
如何实现类似google的图片隐形水印添加和识别技术?
linux上如何运行任意windows程序?
ai能写出比黑客还厉害的零日漏洞等攻击工具攻击任意软件系统工程?
js如何获取浏览器的音频上下文指纹、Canvas指纹、WebGL渲染特征?
为啥ai开始抛弃markdown文本,重新偏好html文本了?
网站有没有办法鉴别访问请求是由ai操控chrome-devtools-mcp发出的?


