キーワードを含むニュース記事の感情を返す小さな Web アプリを作成しようとしています。
TextBlob と Newspaper3K python 3 パッケージを使用しました。Newspaper3K の URL 文字列を Google ニュースの検索クエリの結果にしようとしましたが、新聞パッケージは Google ニュースの「メイン ページ」にリダイレクトされるようです。
特定のキーワードを含む新聞記事のリストを取得する方法はありますか? さらに、新聞がページを繰り返すことは可能ですか?
以下は私のコードです:
from textblob import TextBlob
import newspaper
#keyword = input("Please enter the keyword: ")
keyword = "Apple" #for testing only
keyword_lowercase = keyword.lower()
search_string = "" # only for google news
split_keyword = keyword.split()
for i in range(len(split_keyword)):
search_string += split_keyword[i]
if i != len(split_keyword)-1:
search_string += '+'
def google_news_site(search_query):
prefix = 'http://news.google.com/news?q='
return prefix+search_string
#Currently for news.google.com only
url_string = google_news_site(search_string)
paper = newspaper.build(url_string, memoize_articles=False)
def sentiment(text):
return TextBlob(text).sentiment.polarity
current_sum = 0.0
relevant_article_count = 0
for article in paper.articles:
print(article.url)
article_text = article.text
article_text_lowercase = article_text.lower()
if keyword_lowercase in article_text_lowercase:
current_sum += sentiment(article_text)
print("Article count is", str(relevant_article_count)+".")
rating = current_sum/max(relevant_article_count, 1)
print("The rating for", keyword, "is", str(rating)+".")