【发布时间】:2019-08-11 23:20:58
【问题描述】:
我有一个与 twitter 主题标签相关的字符串列表。我想删除 整个 以特定前缀开始的字符串。
例如:
testlist = ['Just caught up with #FlirtyDancing. Just so cute! Loved it. ', 'After work drinks with this one @MrLukeBenjamin no dancing tonight though @flirtydancing @AshleyBanjo #FlirtyDancing pic.twitter.com/GJpRUZxUe8', 'Only just catching up and @AshleyBanjo you are gorgeous #FlirtyDancing', 'Loved working on this. Always a pleasure getting to assist the wonderful @kendrahorsburgh on @ashleybanjogram wonderful new show !! #flirtydancing pic.twitter.com/URMjUcgmyi', 'Just watching #FlirtyDancing & \n@AshleyBanjo what an amazing way to meet someone.. It made my heart all warm & fuzzy for these people! both couples meet back up.. pic.twitter.com/iwCLRmAi5n',]
我想删除图片 URL、主题标签和 @ 的
到目前为止,我已经尝试了一些方法,即使用startswith() 方法和replace() 方法。
例如:
prefixes = ['pic.twitter.com', '#', '@']
bestlist = []
for line in testlist:
for word in prefixes:
line = line.replace(word,"")
bestlist.append(line)
这似乎摆脱了“pic.twitter.com”,但不是 URL 末尾的一系列字母和数字。这些字符串是动态的,每次都会有不同的结束 URL...这就是为什么如果它们以该前缀开头,我想去掉整个字符串。
我也尝试对所有内容进行标记,但 replace() 仍然无法摆脱整个单词:
import nltk
for line in testlist:
tokens = nltk.tokenize.word_tokenize(line)
for token in tokens:
for word in prefixes:
if token.startswith(word):
token = token.replace(word,"")
print(token)
我开始对startswith() 方法和replace() 方法失去希望,觉得我可能用这两个方法找错了。
有没有更好的方法来解决这个问题?我怎样才能达到删除所有以#、@和pic.twitter开头的字符串的预期结果?
【问题讨论】:
标签: python string data-cleaning