1

Intento obtener polaridad puntuación sobre oraciones sentences. Sin embargo parece que las oraciones están en codificado en bytes. Lo que plantea un problema AttributeError: hasta que objeto bytes no tiene atributo 'encode' para calcular polaridad puntuación con sid.polarity_scores(sentence).

from nltk.sentiment.vader import SentimentIntensityAnalyzer
import unicodedata
sid = SentimentIntensityAnalyzer()
for date, row in df_stocks.T.iteritems():
    try:
        sentence = unicodedata.normalize('NFKD', df_stocks.loc[date, 'articles']).encode('ascii','ignore')
        print(sentence)
        ss = sid.polarity_scores(sentence)

Por consiguiente no funciona :

b" What Sticks from '06. Somalia Orders Islamists to Turn in Weapons. Tehran Radio Lets Critics Vent Over Irans Nuclear Plans. Romania and Bulgaria Join European Union. Two Believed Dead in Madrid Airport Bombing. Edges and Order. Less Shoplifting in Health and Beauty Aisle. At Sea With a Book to Read, and the Author of It, Too. Bombs in Bangkok Kill 2 and Wound More Than 30. A Century Later, Los Angeles Atones for Water Sins. Nonrenewal of TV License Stokes Debate in Venezuela. The Hope of a Fresh Start. Share Grandmas Birthday, With Music and Animation. A New Middle Stance Emerges in Debate over Climate. Pilots Search for Lost Travelers in Colorado as Snow Heads East. With Renovations Set for Official Residence, U.N. Chief Cant Unpack Yet. Environmental Harmony. 3,000 Deaths in Iraq, Countless Tears at Home. The Sleepy Subject of Canadas Grain Exports Perks Up. Marsh & McLennan to Sell Putnam Funds to Canadian Group. Chief Justice Advocates Higher Pay for Judiciary. States Take Lead on Ethics Rules for Lawmakers. U.S. Questioned Iraq on the Rush to Hang Hussein. Songwriters Death Leads to Suits Against Preacher. Department of Household Security. Another Last Chance to Change Your Life. Russia-Belarus Gas Deal Averts Feared Disruptions in Europe. The Not Wanted Signs. Supporters of Thai Ex-Premier Blamed for Blasts. From Father to Son, Last Words to Live By. Follys Antidote. Satellite Radio May Try a Merger. Names of the Dead. This Remaking of Downtown Has Downside. Romania and Bulgaria Dance Into Union. Somali Clan Elders Urge Islamists to Leave Stronghold. The Lonely Newspaper Reader. A Healthy New Year. For Sunnis, Dictators Degrading End Signals Ominous Dawn for the New Iraq. Studios DVDs Face a Crack in Security. Hard Choices Over Video of Execution. New Journal Hits a Closed Market. In Silicon Valley, the Race Is On to Trump Google. CITIC of China Buys Kazakhstan Oil Assets. Costly Gift From Microsoft Is an Invitation to Blog. Something Wiki Is Coming to the Web Search Market. Disney Plans to Introduce a Sleek Makeover of Disney.com Site. New Secretary Makes Choices for U.N. Posts. Ban on Smoking Begins Today in Hong Kong. Hamas Reports Progress on Freeing Israeli Soldier. The Burden of an Unsolved Case and Its Nameless Victim. 2006 Called the Deadliest Year for Journalists and Media Workers. Death Sentences Rise in Japanese Courts. Estimates of Iraqi Civilian Deaths"
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-30-f4f3d67adc77> in <module>
      6         sentence = unicodedata.normalize('NFKD', df_stocks.loc[date, 'articles']).encode('ascii','ignore')
      7         print(sentence)
----> 8         ss = sid.polarity_scores((sentence))
      9         df.set_value(date, 'compound', ss['compound'])
     10         df.set_value(date, 'neg', ss['neg'])

C:\ProgramData\Anaconda3\lib\site-packages\nltk\sentiment\vader.py in polarity_scores(self, text)
    217         valence.
    218         """
--> 219         sentitext = SentiText(text)
    220         #text, words_and_emoticons, is_cap_diff = self.preprocess(text)
    221 

C:\ProgramData\Anaconda3\lib\site-packages\nltk\sentiment\vader.py in __init__(self, text)
    152     def __init__(self, text):
    153         if not isinstance(text, str):
--> 154             text = str(text.encode('utf-8'))
    155         self.text = text
    156         self.words_and_emoticons = self._words_and_emoticons()

AttributeError: 'bytes' object has no attribute 'encode'

Entonces utilicé str(sentences) para obtener la puntuación con sid.polarity_scores(text). Funciona pero hay mejores maneras de

1 respuesta 1

1

Tienes esta línea:

sentence = unicodedata.normalize('NFKD', df_stocks.loc[date, 'articles']).encode('ascii','ignore')

de la que se deduce que:

  • Tus datos de entrada están en df_stocks.loc[date, 'articles'] y ese dato ya viene como cadena unicode (pues si no te habría dado error al pasarlo como parámetro a unicodedata.normalize())
  • Por alguna razón, quieres "normalizarlo" con el esquema NFKD. El resultado de esa normalización es otra vez una cadena unicode.
  • Pero a continuación, sobre ese resultado, haces .encode("ascii", "ignore")y aquí es donde lo conviertes en bytes.

Por tanto lo más sencillo sería eliminar esa conversión final (el .encode()). O incluso puedes plantearte hacer directamente:

sentence = df_stocks.loc[date, 'articles']

pues no explicas por qué o para qué haces la normalización Unicode.

1
  • Si, tienes razón y no sé porque hizo la normalización Unicode porque proviene de este código que intento probar. Entonces si la normalización Unicode sirve a nada voy a cambiar con sentence = df_stocks.loc[date, 'articles']. el 14 dic. 2018 a las 13:49

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.