如何在MonkeyLearn中仅获取并展示tag_name而非完整文本结果
tag_name from MonkeyLearn Classification Response The error you're seeing ('MonkeyLearnResponse' object has no attribute 'classifications') happens because the classifications data isn't a direct property of the response object—it's nested inside the response.body structure.
Here's how to correctly extract just the tag_name values from your classification results:
Step-by-Step Solution
- First, confirm the structure of
response.body: it's a list where each item corresponds to one of your input texts. Each item contains aclassificationsarray (which may have multiple entries if your model returns multiple tags with confidence scores). - Iterate over the response body to access each text's classifications, then pull out the
tag_namefrom each classification.
Corrected Code
from monkeylearn import MonkeyLearn ml = MonkeyLearn('xxxx') data = ['your input text here', 'another text to classify'] # Replace with your actual data model_id = 'xxxx' response = ml.classifiers.classify(model_id, data) # Extract tag_name for each classification for result in response.body: # Get all classifications for the current text classifications = result['classifications'] for classification in classifications: print(classification['tag_name']) # This will print each tag name
If You Only Want the Top (Highest Confidence) Tag
Most models return classifications sorted by confidence (highest first). If you just need the top tag for each text:
for result in response.body: if result['classifications']: # Ensure there are classifications to avoid errors top_tag = result['classifications'][0]['tag_name'] print(top_tag)
Why Your Original Approach Failed
The MonkeyLearnResponse object wraps the raw API response, but the actual classification data lives inside response.body. Trying to call response.classifications directly looks for an attribute that doesn't exist on the response object itself—hence the error.
内容的提问来源于stack exchange,提问作者Soham Shashank Munnangi

