如何从列表的句子中移除@开头或包含https的指定单词?
How to Filter Words Starting with @ or Containing HTTPS from Sentences
Got it, let's fix your code to achieve exactly what you need—removing only the unwanted words (not entire sentences) from your list. Here's the complete implementation:
Step-by-Step Code
First, let's start with your original list and process each sentence individually:
# Your original list of sentences res = ['Today is a great day', 'lunch @myplace', 'make sure to check this link: https://'] # Process each sentence to filter out unwanted words cleaned_sentences = [] for sentence in res: # Split the sentence into individual words words = sentence.split() # Keep only words that don't start with @ and don't contain 'https' filtered_words = [word for word in words if not word.startswith('@') and 'https' not in word] # Join the filtered words back into a proper sentence cleaned_sentences.append(' '.join(filtered_words)) # Let's see the result! print(cleaned_sentences)
Output
Running this code will give you:
['Today is a great day', 'lunch', 'make sure to check this link:']
One-Liner Version (if you prefer conciseness)
You can also condense this into a single list comprehension for brevity:
cleaned_sentences = [' '.join([word for word in s.split() if not word.startswith('@') and 'https' not in word]) for s in res]
Bonus: Case-Insensitive HTTPS Check
If you need to handle cases where 'HTTPS' is in uppercase (like HTTPS://example.com), modify the filter condition to use lowercase for the check:
filtered_words = [word for word in words if not word.startswith('@') and 'https' not in word.lower()]
This way, any variation of 'https' (uppercase, mixed case) will be caught and the corresponding word removed.
内容的提问来源于stack exchange,提问作者Nienke Luirink
相关产品推荐
相关产品推荐

