从推文列表中删除推特用户名的最佳方法?
Best way to remove twitter user names from list of tweets?
如果推文中存在用户名,我正在尝试找到从用户推文中删除推特用户名的最佳方法。例如,我有一组存储的推文,我想 return 像这样取出用户名的推文
tweets = ['@joe123 thank you', 'this reminds me of @john12', 'this tweet has no username tag in it']
clean_tweets = ['thank you', 'this reminds me of', 'this tweet has no username tag in it']
这是我目前的情况:
tweets = ['@joe123 thank you', 'this reminds me of @john12', 'this tweet has no username tag in it']
clean_tweets = [word for tweet in tweets for word in tweet.split() if not word.startswith('@')]
然而输出看起来像这样:
['thank',
'you',
'this',
'reminds',
'me',
'of',
'this',
'tweet',
'has',
'no',
'username',
'tag',
'in',
'it']
除了使用嵌套列表理解之外,我希望有更好的方法来解决这个问题。也许使用 lambda 的应用函数会更好?有什么帮助谢谢
方法有很多种。例如,使用正则表达式:将 @ 后跟至少一个字母数字符号替换为空字符串。
import re
[re.sub(r'@\w+', '', x) for x in tweets]
#['thank you', 'this reminds me of', 'this tweet has no username tag in it']
试试这个列表理解:
clean_tweets = [" ".join([word for word in tweet.split() if not word.startswith('@')]) for tweet in tweets]
[word for word in tweet.split() if not word.startswith('@')]
- 给定一条推文,将其拆分为单词,然后 return 未提及的单词列表
" ".join()
- 将该列表转回字符串
[... for tweet in tweets]
- 对每条推文执行此操作
如果推文中存在用户名,我正在尝试找到从用户推文中删除推特用户名的最佳方法。例如,我有一组存储的推文,我想 return 像这样取出用户名的推文
tweets = ['@joe123 thank you', 'this reminds me of @john12', 'this tweet has no username tag in it']
clean_tweets = ['thank you', 'this reminds me of', 'this tweet has no username tag in it']
这是我目前的情况:
tweets = ['@joe123 thank you', 'this reminds me of @john12', 'this tweet has no username tag in it']
clean_tweets = [word for tweet in tweets for word in tweet.split() if not word.startswith('@')]
然而输出看起来像这样:
['thank',
'you',
'this',
'reminds',
'me',
'of',
'this',
'tweet',
'has',
'no',
'username',
'tag',
'in',
'it']
除了使用嵌套列表理解之外,我希望有更好的方法来解决这个问题。也许使用 lambda 的应用函数会更好?有什么帮助谢谢
方法有很多种。例如,使用正则表达式:将 @ 后跟至少一个字母数字符号替换为空字符串。
import re
[re.sub(r'@\w+', '', x) for x in tweets]
#['thank you', 'this reminds me of', 'this tweet has no username tag in it']
试试这个列表理解:
clean_tweets = [" ".join([word for word in tweet.split() if not word.startswith('@')]) for tweet in tweets]
[word for word in tweet.split() if not word.startswith('@')]
- 给定一条推文,将其拆分为单词,然后 return 未提及的单词列表
" ".join()
- 将该列表转回字符串
[... for tweet in tweets]
- 对每条推文执行此操作