首页 > 解决方案 > 从 Pandas 列中删除 Twitter 提及

问题描述

我有一个数据集,其中包括来自 Twitter 的推文。其中一些也有用户提及,例如@thisisauser. 我尝试在执行其他清洁过程的同时删除该文本。

def clean_text(row, options):

    if options['lowercase']:
        row = row.lower()

    if options['decode_html']:
        txt = BeautifulSoup(row, 'lxml')
        row = txt.get_text()

    if options['remove_url']:
        row = row.replace('http\S+|www.\S+', '')

    if options['remove_mentions']:
        row = row.replace('@[A-Za-z0-9]+', '')

    return row

clean_config = {
    'remove_url': True,
    'remove_mentions': True,
    'decode_utf8': True,
    'lowercase': True
    }

df['tweet'] = df['tweet'].apply(clean_text, args=(clean_config,))

但是,当我运行上面的代码时,所有 Twitter 提及的内容仍然在文本中。我使用 Regex 在线工具验证了我的 Regex 工作正常,所以问题应该出在 Pandas 的代码上。

标签: pythonregexpandas

解决方案


replace在字符串上滥用方法,因为它不接受正则表达式,只接受固定字符串(有关更多信息,请参阅https://docs.python.org/2/library/stdtypes.html#str.replace上的文档)。

满足您需求的正确方法是使用re如下模块:

import re
re.sub("@[A-Za-z0-9]+","", "@thisisauser text")
' text'

推荐阅读