点此进入CSDN

点此添加QQ好友 加载失败时会显示




python 快速替换csv数据集字符串列表中的表情符号为空,asyncio,re,pandas

 

传统的字符串列表替换字符串使用遍历非常慢

比如下面这段代码,如果处理几十万或上百万的数据集时,会非常的慢,几小时几天都可能

import re

p = re.compile(u'['u'\U0001F300-\U0001F64F' u'\U0001F680-\U0001F6FF' u'\u2600-\u2B55 \U00010000-\U0010ffff]+')
# text = "超详细修高鼻梁教程,点❤️收藏慢慢看#美妆 #使用一次你就喜欢"
# txt = re.sub(p,'',text) # 正则匹配,将表情符合替换为空''
# print(txt)

bar = tqdm(enumerate(data['text']),total=len(data['text']))
for idx,text in bar:
data['text'][idx] = re.sub(p,'',text)

data

  

如何加速,使用异步携程加速,同时创建多个携程,使用多个携程同时处理字符串,有个对比,66w的数据只需不到1分钟即可处理完

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import re
import pandas as pd
import asyncio
 
async def replace_emoji(text):
    # 表情的Unicode编码范围
    emoji_pattern = re.compile("[\U0001F600-\U0001F64F\U0001F300-\U0001F5FF\U0001F680-\U0001F6FF\U0001F1E0-\U0001F1FF]", flags=re.UNICODE)
    # 替换表情为空
    new_text = emoji_pattern.sub('', text)
    return new_text
 
async def main():
    # 读取CSV文件
    df = pd.read_csv('file.csv')
    # 创建一个事件循环
    loop = asyncio.get_event_loop()
    # 异步替换所有文本中的表情
    replaced_text = await asyncio.gather(*[loop.create_task(replace_emoji(text)) for text in df['text']])
    # 将替换后的文本保存回CSV文件的text列
    df['text'] = replaced_text
    df.to_csv('file.csv', index=False)
 
# 运行主程序
asyncio.run(main())

  

posted @   高颜值的殺生丸  阅读(96)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
历史上的今天:
2020-04-26 实体识别中,或序列标注任务中的维特比Viterbi解码

作者信息

昵称:

刘新宇

园龄:4年6个月


粉丝:1209


QQ:522414928

点击右上角即可分享
微信分享提示