首页 > 解决方案 > KeyError:“爱”。请帮我找到解决方案

问题描述

def sentence_to_avg(sentence, word_to_vec_map):
    # Get a valid word contained in the word_to_vec_map. 
    any_word = list(word_to_vec_map.keys())[0]
    
    ### START CODE HERE ###
    # Step 1: Split sentence into list of lower case words (≈ 1 line)
    words = (sentence.lower()).split()

    # Initialize the average word vector, should have the same shape as your word vectors.
    avg = np.zeros((word_to_vec_map[words[0]].shape))
    
    # Initialize count to 0
    count = 0
    
    # Step 2: average the word vectors. You can loop over the words in the list "words".
    for w in words:
        # Check that word exists in word_to_vec_map
        if w in word_to_vec_map:
            avg += word_to_vec_map[w]
            # Increment count
            count +=1
          
    if count > 0:
        # Get the average. But only if count > 0
        avg = avg / len(words)
    
    ### END CODE HERE ###
    
    return avg

以下代码给出错误:KeyError:'love'。请帮我确定问题。我尝试了各种组合,但都没有奏效

标签: pythonnlp

解决方案


您可以改用这条线

avg = np.zeros(word_to_vec_map[any_word].shape)

if count > 0:
    # Get the average. But only if count > 0
    avg = avg / count

推荐阅读