多句子按指定关键词分类报错:‘in’要求左操作数为字符串而非列表
Let's break down what's going wrong and fix your code step by step.
The Root Cause of the Error
Your original code uses if y in i: where y is a list (like ["web", "online"]) and i is a single string sentence. Python's in operator expects the left operand to be a single element (like a string) when checking membership in another string—you can't ask if an entire list is a substring of a string, which is why you get the in requires string as left operand, not list error.
Revised Code to Handle Keyword Lists
First, let's adjust the function to properly check for any keyword in the sentence, assign the corresponding category, and avoid global variable issues (your original b list is global, which can cause unexpected behavior on repeated calls):
# Your input data data = ["my web portal is not working","online is better than offline", "i like going to pharmacy shop for medicines"] words = ["web", "online"] def classify_sentences(sentences, keywords): classified_results = [] for sentence in sentences: matched_category = None # Check each keyword to see if it exists in the sentence for keyword in keywords: if keyword in sentence: matched_category = keyword # Use the keyword as the category (customize this if needed) break # Stop checking once we find a match # Append the matched category or "other" if no keywords were found classified_results.append(matched_category if matched_category else "other") return classified_results # Test the function print(classify_sentences(data, words)) # Output: ['web', 'online', 'other']
Key Improvements
- No global variables: We create the result list inside the function, so each call returns a fresh set of classifications without leftover data.
- Proper keyword checking: Instead of comparing a list to a string, we iterate through each keyword and check if it's present in the sentence.
- Clear category mapping: The code assigns the matching keyword as the category (you can easily change this to custom category names, like
"web_service"instead of"web"if needed).
Simplified Version (If You Don't Need Specific Keyword Categories)
If you just need to mark sentences as "relevant" (containing any keyword) or "other", you can use a list comprehension with any() for a more concise solution:
def classify_sentences(sentences, keywords): return [ "relevant" if any(key in sentence for key in keywords) else "other" for sentence in sentences ]
This will return ['relevant', 'relevant', 'other'] for your input data.
内容的提问来源于stack exchange,提问作者anant

