[英]Removing certain words from sentences in a list
如果我有一个包含某些句子和单词的列表,例如:
res = ['Today is a great day', 'lunch @myplace', 'make sure to check this link: https://']
而我只想删除以'@'开头的单词或包含'https'的单词,而不删除包含该单词的整个句子,我该怎么做? 现在,我有以下内容:
words_filtered = [e.lower() for e in res]
words_cleaned = [word for word in words_filtered if 'http' not in word and not word.startswith('@')]
在打印words_cleaned时,确实从列表中删除了这些单词,但整个句子也删除了。 它返回['今天是美好的一天']但我希望它返回['今天是美好的一天','午餐','确保检查此链接:']
在这里赞美理解的力量:
res = ['Today is a great day', 'lunch @myplace', 'make sure to check this link: https://']
words_cleaned = [" ".join([
words for words in sentence.split()
if 'https:' not in words and not words.startswith('@')])
for sentence in res]
print(words_cleaned)
这产生
['Today is a great day', 'lunch', 'make sure to check this link:']
@jpp
指出的那样,使用
words_cleaned = [" ".join([ words for words in sentence.split() if not ('https' in words or words.startswith('@'))]) for sentence in res]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.