python - 从 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 的代码上。
解决方案
您replace
在字符串上滥用方法,因为它不接受正则表达式,只接受固定字符串(有关更多信息,请参阅https://docs.python.org/2/library/stdtypes.html#str.replace上的文档)。
满足您需求的正确方法是使用re
如下模块:
import re
re.sub("@[A-Za-z0-9]+","", "@thisisauser text")
' text'
推荐阅读
- python - 在 python 中使用 Mockito 模拟方法
- reactjs - 如何在组件渲染内对条件(分支)进行单元测试(返回前)
- scala - 在 Akka 类型中,如何反序列化没有 ActorSystem 的序列化 ActorRef?
- python-3.x - 芹菜-禁用信号
- python - Gstreamer 自动插入:在“have-type”上创建 demux
- c# - 如何为我的财产创建自定义事件
- asp.net-mvc - 无法弄清楚如何使用下一个和上一个按钮使元素分页
- python-3.x - 如何将两行分钟的时间不同值转换为小时
- c# - 如何确定用户是否不包含角色
- python - Python,无法将变量传递给KafkaConsumer