Yelp网站报废

时间:2020-07-29 22:35:28

标签: python pandas dataframe web-scraping jupyter-notebook

在Jupyter笔记本上运行代码时,遇到了此错误。我安装了matplotlibpandas。有谁知道这可能是什么? 代码:

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的网站进行网页搜刮

1 个答案:

答案 0 :(得分:0)

问题:

NameError:未定义名称“ word”。您正在尝试访问单词,但单词显然未定义。

可能的解决方案:

我认为正确的return语句是这样的:

return sum(len(word) for word in words) / len(words)

(我在for word in words中切换了单词单词,因为我认为单词是数组而不是单词)