在Jupyter notebook上运行代码时,我遇到了这个错误。我安装了matplotlib和pandas。有人知道这会是什么吗?代码:
def average_words(x):
words = x.split()
return sum(len(word) for words in word) / len(words)
df['average_word_length'] = df['review'].apply(lambda x: average_words(x))
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-102-bbc583af9f13> in <module>
----> 1 df['average_word_length'] = df['review'].apply(lambda x: average_words(x))
/opt/anaconda3/envs/py36/lib/python3.6/site-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds)
3846 else:
3847 values = self.astype(object).values
-> 3848 mapped = lib.map_infer(values, f, convert=convert_dtype)
3849
3850 if len(mapped) and isinstance(mapped[0], Series):
pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()
<ipython-input-102-bbc583af9f13> in <lambda>(x)
----> 1 df['average_word_length'] = df['review'].apply(lambda x: average_words(x))
<ipython-input-96-4f4dfe065b11> in average_words(x)
1 def average_words(x):
2 words = x.split()
----> 3 return sum(len(word) for words in word) / len(words)
NameError: name 'word' is not defined需要说明的是,我正在尝试从Yelp的网站上进行Web抓取
发布于 2020-07-30 06:46:17
问题:
NameError:未定义名称'word‘。您正在尝试访问word,但word显然未定义。
可能的解决方案:
我认为正确的返回语句是这样的:
return sum(len(word) for word in words) / len(words)
(我在for word in words中切换了word和 words ,因为我假设words是数组,而不是word)
https://stackoverflow.com/questions/63163454
复制相似问题