python - 从文本文件中提取与输入单词最相似的前 N ​​个单词

标签 python deep-learning nlp spacy gensim

我有一个文本文件,其中包含我使用 BeautifulSoup 提取的网页内容。我需要根据给定的单词从文本文件中找到 N 个相似的单词。流程如下:

  1. 从中提取文本的网站:https://en.wikipedia.org/wiki/Football
  2. 提取的文本将保存到文本文件中。
  3. 用户输入一个单词,例如:“目标”,我必须显示文本文件中前 N 个最相似的单词。

我只从事计算机视觉工作,对 NLP 完全陌生。我目前陷入了第3步。我尝试过Spacy和Gensim,但我的方法一点效率都没有。我目前这样做:

for word in ['goal', 'soccer']:
    # 1. compute similarity using spacy for each word in the text file with the given word.
    # 2. sort them based on the scores and choose the top N-words.

有没有其他方法或简单的解决方案来解决这个问题?任何帮助表示赞赏。谢谢!

最佳答案

您可以利用 spacy similarity方法,它将为您计算标记之间的余弦相似度。为了使用向量,请加载带有向量的模型:

import spacy
nlp = spacy.load("en_core_web_md")

text = "I have a text file that contains the content of a web page that I have extracted using BeautifulSoup. I need to find N similar words from the text file based on a given word. The process is as follows"
doc = nlp(text)
words = ['goal', 'soccer']

# compute similarity    
similarities = {}   
for word in words:
    tok = nlp(word)
    similarities[tok.text] ={}
    for tok_ in doc:
        similarities[tok.text].update({tok_.text:tok.similarity(tok_)})

# sort
top10 = lambda x: {k: v for k, v in sorted(similarities[x].items(), key=lambda item: item[1], reverse=True)[:10]}

# desired output
top10("goal")
{'need': 0.41729581641359625,
 'that': 0.4156277030017712,
 'to': 0.40102258054859163,
 'is': 0.3742535591719576,
 'the': 0.3735002888862756,
 'The': 0.3735002888862756,
 'given': 0.3595024941701789,
 'process': 0.35218102758578645,
 'have': 0.34597281472837316,
 'as': 0.34433650293640194}

请注意,(1) 如果您熟悉 gensim,和/或 (2) 有一个针对您的文本训练的 word2vec 模型,您可以直接执行以下操作:

word2Vec.most_similar(positive=['goal'], topn=10)

关于python - 从文本文件中提取与输入单词最相似的前 N ​​个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64630194/

相关文章:

python - 在 Luigi Orchestrator 任务的运行函数中使用 luigi.DateParameter

python - 如何将 n-grams 组合成 Spark 中的一个词汇表?

python - 函数调用堆栈 : keras_scratch_graph Error

python - 查找特定词汇并提取 csv 行并在新 csv 文件中进行转换

python - 如何将c类型和python类型组合成一个结构体?

python - 获取一组中多个分组的 pandas.DataFrame 聚合中每个子组的计数

python - relu 作为 Dense() (或任何其他层)中的参数与 ReLu 作为 Keras 中的层

python - Caffe 网络损失非常低,但测试精度非常差

python - tensorflow 如何进行CNN计算?

python - 在python中,如何计算特定日期超过 "base date"有多少天?