python - 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'。请帮我确定问题。我尝试了各种组合,但都没有奏效
解决方案
您可以改用这条线
avg = np.zeros(word_to_vec_map[any_word].shape)
和
if count > 0:
# Get the average. But only if count > 0
avg = avg / count
推荐阅读
- python - 提取python字符串中给定键的值
- c# - 如何在 Xamarin 上显示弹出窗口
- python - 无法在 Windows 上使用 pip3 install 安装 ifxpy 包
- git - 如何强制中止或终止 Git rebase
- python - 我是否需要使用后端功能来自定义 Keras 损失
- arrays - 选择 Typescript 中的 JSON 到数组绑定
- angular - 如何使用从@Output 发射器接收的角度反应形式的数组将formControl 的formArray 初始化为formGroup?
- c++ - 从 concurrent_unordered_map 中删除项目列表
- javascript - 如何在节点 js 中解压缩 .prproj 文件(premier pro 项目)?
- java - 通知 FCM android java 不起作用服务处理意图的时间太长:com.google.android.c2dm.intent.RECEIVE 应用程序可能会关闭