【问题标题】:Best way to remove twitter user names from list of tweets? [duplicate]从推文列表中删除推特用户名的最佳方法? [复制]
【发布时间】:2021-03-20 06:53:03
【问题描述】:

如果推文中存在用户名,我正在尝试找到从用户推文中删除推特用户名的最佳方法。例如,我有一个存储的推文数组,我想返回推文,并像这样取出用户名

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 的应用函数会更好地工作?有什么帮助谢谢

【问题讨论】:

    标签: python string split data-cleaning


    【解决方案1】:

    有很多方法。比如说,使用正则表达式:用空字符串替换后跟至少一个字母数字符号的 @。

    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']
    

    【讨论】:

    • 出于好奇,有没有办法用一个正则表达式删除多余的空格?我想到了r' ?@\w+ ?',虽然它有时会处理它,但它通常会删除太多。我想您可以r'@\w+' 删除提及,然后将双空格更改为单空格,但是可以在一个语句中完成吗?
    • 更新删除空格。
    • 问题在于像“hey @mention what's up”这样的字符串你会得到“heywhat's up”——这就是我删除太多空格的意思。
    • @thshea 够公平的。
    【解决方案2】:

    试试这个列表理解:

    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('@')] - 给定一条推文,将其拆分为单词,然后返回未提及的单词列表

    " ".join() - 将该列表转回字符串

    [... for tweet in tweets] - 每条推文都这样做

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-21
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      • 2018-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多