我有一个有关推文的列表,我需要删除用户名。
[['@Hegelbon','That','heart','sliding','into','the','waste','basket','.',':('],['“','@ketchBurning',':','I','hate','Japanese','call','him','"','bani','"',
':(',':(','”','Me','too'], ... ]
主要问题是我不知道如何使用列表列表。我尝试了以下代码,但没有用:
import re
for element in tweets:
for word in element:
re.sub('@[^\s]+','', tweets)
请帮助。
答案 0 :(得分:2)
您可以使用嵌套列表推导来过滤以@
开头的字符串(假设列表列表存储为变量l
):
[[i for i in s if not i.startswith('@')] for s in l]
这将返回:
[['That', 'heart', 'sliding', 'into', 'the', 'waste', 'basket', '.', ':('], ['“', ':', 'I', 'hate', 'Japanese', 'call', 'him', '"', 'bani', '"', ':(', ':(', '”', 'Me', 'too']]
答案 1 :(得分:1)
使用列表迭代:
mylist = [['@Hegelbon','That','heart','sliding','into','the','waste','basket','.',':('],['“','@ketchBurning',':','I','hate','Japanese','call','him','"','bani','"',
':(',':(','”','Me','too'] ]
newlist = [ [item for item in sublist if not item.startswith('@')] for sublist in mylist]