【问题标题】:convert spacy hash back to string - after using .vocab使用 .vocab 后将 spacy 哈希转换回字符串
【发布时间】:2022-10-13 12:13:22
【问题描述】:

我有以下代码:

import spacy
nlp = spacy.load('en_core_web_lg')
word = nlp.vocab["world"]
final_synonym = ['universe','existence','creation','cosmos','macrocosm','domain','reality','earth','globe','populace','public','earthly_concern','human_race','humanity','humankind','human_beings','humans','mankind','man','global','planetary']

我想创建一个字典来存储单词和 final_synonym 中每个元素之间的相似性。

spacy_results = []
for i in range(len(final_synonym)):
    final_synonym[i] = nlp.vocab[final_synonym[i]]
    spacy_similarity = word.similarity(final_synonym[i])
    spacy_results.append(spacy_similarity)

现在,如果我创建字典:

res = {}
for key in final_synonym:
    for value in spacy_results:
        res[key] = value
        spacy_results.remove(value)
        break

一切都很好,但列表 final_synonym 现在包含每个元素的散列而不是字符串。如何将 spacy 哈希转换回以前的字符串?

我的结果是:

{<spacy.lexeme.Lexeme at 0x24fc0b06b00>: 0.6718395948410034,
 <spacy.lexeme.Lexeme at 0x24fc0b06600>: 0.4913380742073059,
 <spacy.lexeme.Lexeme at 0x24fc0ad3e40>: 0.3789522051811218,
 <spacy.lexeme.Lexeme at 0x24fc0b06840>: 0.4318424463272095,
 <spacy.lexeme.Lexeme at 0x24fc0b06cc0>: 0.3014813959598541,
 <spacy.lexeme.Lexeme at 0x24fc0ad1f00>: 0.23181180655956268,
 <spacy.lexeme.Lexeme at 0x24fc0ad1a80>: 0.5879489183425903,
 <spacy.lexeme.Lexeme at 0x24fc0ad1dc0>: 0.49156078696250916,
 <spacy.lexeme.Lexeme at 0x24fc0ad1e40>: 0.7273148894309998,
 <spacy.lexeme.Lexeme at 0x24fc0b03d40>: 0.4184108078479767,
 <spacy.lexeme.Lexeme at 0x24fc0ad1580>: 0.31901150941848755,
 <spacy.lexeme.Lexeme at 0x24fc0ad1900>: 0.0,
 <spacy.lexeme.Lexeme at 0x24fc0b00140>: 0.0,
 <spacy.lexeme.Lexeme at 0x24fc0aeee00>: 0.6186776161193848,
 <spacy.lexeme.Lexeme at 0x24fc0ad1cc0>: 0.6014578938484192,
 <spacy.lexeme.Lexeme at 0x24fc0ad1740>: 0.0,
 <spacy.lexeme.Lexeme at 0x24fc0ad1380>: 0.49049633741378784,
 <spacy.lexeme.Lexeme at 0x24fc0ad1980>: 0.5243041515350342,
 <spacy.lexeme.Lexeme at 0x24fc0ad1680>: 0.25401803851127625,
 <spacy.lexeme.Lexeme at 0x24fc0ad1480>: 0.5530120730400085,
 <spacy.lexeme.Lexeme at 0x24fc0ad12c0>: 0.42649978399276733}

【问题讨论】:

    标签: python nlp spacy


    【解决方案1】:

    vocab(或者更准确地说,它使用的 StringStore)适用于字符串到散列或散列到字符串的转换,因此您可以使用nlp.vocab.strings[hash] 来获取字符串。请注意,如果您为 Vocab 未见过的字符串提供哈希,您将收到错误消息。您可以阅读有关此in the dev docs 的更多信息。

    也就是说,您是否有理由不只在字典中使用字符串键?看起来你可以通过不使用 for 循环中的第一行来完全避免这种情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-02
      • 2016-10-21
      • 1970-01-01
      • 2018-11-08
      • 2019-08-26
      • 2015-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多