pandas HTTP错误400:错误请求(在py中使用textblob)

wribegjk  于 2023-04-10  发布在  其他
关注(0)|答案(1)|浏览(146)

我正在用textblob试验一些问题...我从Tweeter API得到了一个dataframe,我试图通过textblob得到一个情感分析,但由于tooo,我无法做到:

from time import sleep
from textblob.exceptions import NotTranslated 
from textblob.exceptions import TranslatorError

def get_polarity(text):
  analysis = TextBlob(text)
  if text != ' ':
    try:
        if analysis.detect_language() == 'es':
          result = analysis.translate(from_lang = 'es', to = 'en').sentiment.polarity
          time.sleep(10)
          return result

        elif analysis.detect_language() != 'es':
          return TextBlob(text)
    except TranslatorError or NotTranslated:
      return TextBlob(text)
    else:
      return TextBlob(text)


df['polarity'] = df.apply(get_polarity)

所有上述返回所有上述返回下一个Traceback....

HTTPError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5456/3601509909.py in <module>
----> 1 df['polarity'] = df['clean_text'].apply(get_polarity)

~\anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwargs)
   4355         dtype: float64
   4356         """
-> 4357         return SeriesApply(self, func, convert_dtype, args, kwargs).apply()
   4358 
   4359     def _reduce(

~\anaconda3\lib\site-packages\pandas\core\apply.py in apply(self)
   1041             return self.apply_str()
   1042 
-> 1043         return self.apply_standard()
   1044 
   1045     def agg(self):

~\anaconda3\lib\site-packages\pandas\core\apply.py in apply_standard(self)
   1096                 # List[Union[Callable[..., Any], str]]]]]"; expected
   1097                 # "Callable[[Any], Any]"
-> 1098                 mapped = lib.map_infer(
   1099                     values,
   1100                     f,  # type: ignore[arg-type]

~\anaconda3\lib\site-packages\pandas\_libs\lib.pyx in pandas._libs.lib.map_infer()

~\AppData\Local\Temp/ipykernel_5456/2552980312.py in get_polarity(text)
      6   if text != ' ':
      7     try:
----> 8         if analysis.detect_language() == 'es':
      9           result = analysis.translate(from_lang = 'es', to = 'en').sentiment.polarity
     10           time.sleep(10)

~\anaconda3\lib\site-packages\textblob\blob.py in detect_language(self)
    595             DeprecationWarning
    596         )
--> 597         return self.translator.detect(self.raw)
    598 
    599     def correct(self):

~\anaconda3\lib\site-packages\textblob\translate.py in detect(self, source, host, type_)
     74             client="te",
     75         )
---> 76         response = self._request(url, host=host, type_=type_, data=data)
     77         result, language = json.loads(response)
     78         return language

~\anaconda3\lib\site-packages\textblob\translate.py in _request(self, url, host, type_, data)
     94         if host or type_:
     95             req.set_proxy(host=host, type=type_)
---> 96         resp = request.urlopen(req)
     97         content = resp.read()
     98         return content.decode('utf-8')

~\anaconda3\lib\urllib\request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
    212     else:
    213         opener = _opener
--> 214     return opener.open(url, data, timeout)
    215 
    216 def install_opener(opener):

~\anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout)
    521         for processor in self.process_response.get(protocol, []):
    522             meth = getattr(processor, meth_name)
--> 523             response = meth(req, response)
    524 
    525         return response

~\anaconda3\lib\urllib\request.py in http_response(self, request, response)
    630         # request was successfully received, understood, and accepted.
    631         if not (200 <= code < 300):
--> 632             response = self.parent.error(
    633                 'http', request, response, code, msg, hdrs)
    634 

~\anaconda3\lib\urllib\request.py in error(self, proto, *args)
    559         if http_err:
    560             args = (dict, 'default', 'http_error_default') + orig_args
--> 561             return self._call_chain(*args)
    562 
    563 # XXX probably also want an abstract factory that knows when it makes

~\anaconda3\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args)
    492         for handler in handlers:
    493             func = getattr(handler, meth_name)
--> 494             result = func(*args)
    495             if result is not None:
    496                 return result

~\anaconda3\lib\urllib\request.py in http_error_default(self, req, fp, code, msg, hdrs)
    639 class HTTPDefaultErrorHandler(BaseHandler):
    640     def http_error_default(self, req, fp, code, msg, hdrs):
--> 641         raise HTTPError(req.full_url, code, msg, hdrs, fp)
    642 
    643 class HTTPRedirectHandler(BaseHandler):

HTTPError: HTTP Error 400: Bad Request

有人能帮我吗?我真的被卡住了,我想我可能有点傻,但我是一个初学者。
谢谢你们

yzuktlbb

yzuktlbb1#

我知道这有点晚了,但是textblob的lang检测和翻译已经被弃用了。请使用谷歌翻译的官方API。

相关问题