我正在对比特币新闻进行情感分析。在我编码期间,发生TypeError问题。希望您能帮到我,非常感谢!
from newsapi.newsapi_client import NewsApiClient
from textblob import TextBlob
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
import datetime
from datetime import time
import csv
from dateutil import parser
api = NewsApiClient(api_key='my key')
all_articles = api.get_everything(q='bitcoin',
sources='bbc-news,the-verge,financial-times,metro,business-insider,reuters,bloomberg,cnbc,cbc-news,fortune,crypto-coins-news',
domains='bbc.co.uk,techcrunch.com',
from_param='2019-10-20',
to='2019-11-19',
language='en')
sort_by='relevancy',
page_size=100)
news= pd.DataFrame(all_articles['articles'])
news['polarity'] = news.apply(lambda x: TextBlob(x['description']).sentiment.polarity, axis=1)
news['subjectivity'] = news.apply(lambda x: TextBlob(x['description']).sentiment.subjectivity, axis=1)
news['date']= news.apply(lambda x: parser.parse(x['publishedAt']).strftime('%Y.%m.%d'), axis=1)
news['time']= news.apply(lambda x: parser.parse(x['publishedAt']).strftime('%H:%M'), axis=1)
然后发生此TypeError:enter image description here
正如@Hayat正确指出的那样,description
列中的某些行具有None
值,这导致了异常。见下文。
您应删除此类行,并对具有适当数据的行进行操作。您可以使用
过滤此类行news_filtered = news[news['description'].notnull()]
news_filtered['polarity'] = news_filtered.apply(lambda x: TextBlob(x['description']).sentiment.polarity, axis=1)
您可能需要对其他列重复以上操作。
您需要调试代码。您正在传递None
值。
[x['description']
中可能有一些None
值。
news['polarity'] = news.apply(lambda x: TextBlob(x['description']).sentiment.polarity, axis=1)
请确保在预处理阶段中None
中没有任何NaN
或dataframe
值