如何统计Python多行/长列表输出中Positive与Negative的出现次数
Hey there! I get why you're frustrated—trying to tally those sentiment labels but only getting the first line's count is super annoying. Let's fix this together.
The Problem With Your Current Approach
When you use sentimentprediction.count('Positive') directly, it’s likely because sentimentprediction isn’t a list of individual labels. It’s either a multi-line string that hasn’t been split into separate entries, or an iterable (like a file handle) that only reads one line at a time instead of storing all results. That’s why you’re only getting the count from the first entry.
Solution 1: Split Multi-Line String Into Individual Labels
If your sentimentprediction is a single string with each label on a new line, split it into a list of lines first, then count:
# Split the multi-line string into a list of individual labels sentiment_labels = sentimentprediction.splitlines() # Count each category positive_count = sentiment_labels.count('Positive') negative_count = sentiment_labels.count('Negative') print(f"Total Positive: {positive_count}") print(f"Total Negative: {negative_count}")
Solution 2: Handle Iterable Objects (Like File Handles)
If sentimentprediction is an iterable (e.g., you’re reading results from a file), first collect all labels into a list (and strip any extra whitespace/newlines to avoid mismatches):
# Collect all labels, stripping extra whitespace/newlines to ensure accurate matching sentiment_labels = [line.strip() for line in sentimentprediction] # Count each category positive_count = sentiment_labels.count('Positive') negative_count = sentiment_labels.count('Negative') print(f"Total Positive: {positive_count}") print(f"Total Negative: {negative_count}")
Bonus: Use collections.Counter for Flexibility
If you ever add more sentiment categories (like Neutral), Counter is a cleaner way to get all counts at once:
from collections import Counter # Get all labels into a list first (using either method above) sentiment_labels = sentimentprediction.splitlines() # Count all unique labels in one go label_counts = Counter(sentiment_labels) print(f"Positive: {label_counts.get('Positive', 0)}") print(f"Negative: {label_counts.get('Negative', 0)}")
Pro Tip
Always double-check for extra whitespace! If your lines have trailing spaces or newline characters (like 'Positive\n'), using strip() will ensure you’re matching the exact label text.
内容的提问来源于stack exchange,提问作者JamesMcFlyJR

