空気読み取り機能
import nltk
from textblob import TextBlob
class AtmosphereReader:
def __init__(self):
self.conversation_history = []
self.tone_analyzer = TextBlob
self.context_keywords = set()
def analyze_input(self, user_input):
# 入力テキストの感情分析
blob = self.tone_analyzer(user_input)
sentiment = blob.sentiment.polarity
# キーワード抽出
tokens = nltk.word_tokenize(user_input)
keywords = [word for word in tokens if word.isalnum()]
self.context_keywords.update(keywords)
# 文脈の分析
context = self.analyze_context()
return sentiment, context
def analyze_context(self):
# 直近の会話履歴から文脈を分析
recent_history = self.conversation_history[-5:]
context = ' '.join(recent_history)
context_blob = self.tone_analyzer(context)
return {
'overall_sentiment': context_blob.sentiment.polarity,
'key_topics': list(self.context_keywords)[-10:] # 最新の10個のキーワード
}
def generate_response(self, sentiment, context):
if sentiment > 0.5:
tone = "非常にポジティブ"
elif sentiment > 0:
tone = "やや前向き"
elif sentiment < -0.5:
tone = "非常にネガティブ"
elif sentiment < 0:
tone = "やや否定的"
else:
tone = "中立"
response = f"現在の雰囲気: {tone}\n"
response += f"主要な話題: {', '.join(context['key_topics'])}\n"
if context['overall_sentiment'] > 0.3:
response += "全体的に良好な雰囲気です。前向きな会話を続けましょう。"
elif context['overall_sentiment'] < -0.3:
response += "少し緊張した雰囲気を感じます。話題を変えてみるのはいかがでしょうか?"
else:
response += "平常的な雰囲気です。特に注意すべき点はありません。"
return response
def process_input(self, user_input):
self.conversation_history.append(user_input)
sentiment, context = self.analyze_input(user_input)
return self.generate_response(sentiment, context)
# 使用例
reader = AtmosphereReader()
print(reader.process_input("今日はとても素晴らしい一日でした!"))
print(reader.process_input("でも、明日の会議が少し心配です。"))