python flashtext字符串快速替换,自然语言处理加速
在自然语言处理当中,经常对数据集进行一些数据字符的替换,表情的替换,以便在tokenizer的时候不被识别成[unk],造成信息的缺失
常规方法使用python自带的replace方法实现,但数据量很大时,效率显得低了
比如下面的代码,处理60000条数据需要3+小时
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | from tqdm.notebook import tqdm emoji_dict = {} with open ( '/Users/xinyuuliu/Desktop/data/emoji/emoji_map_full.txt' ) as f_emoji: emojilist = f_emoji.readlines() for em in emojilist: emoji,emoji_str = em.split(maxsplit = 1 ) emoji_dict[emoji] = emoji_str.strip() # print(emoji_dict) bar = tqdm( enumerate (data[ 'text' ]),total = len (data[ 'text' ])) for idx,text in bar: for em in emoji_dict: text = text.replace(em,emoji_dict[em]) data[ 'text' ][idx] = text # if idx == 10: # break data |
可以看到处理6%的数据已经14分钟了
如何加速,使用flashtext模块,如果会异步就更快了,这里我还没有实现异步
pip install flashtext
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | from flashtext import KeywordProcessor # 1. 初始化关键字处理器 keyword_processor = KeywordProcessor() # 2. 添加关键词 for em in emoji_dict: keyword_processor.add_keyword(em, emoji_dict[em]) # 3. 替换关键词 bar = tqdm( enumerate (data[ 'text' ]),total = len (data[ 'text' ])) for idx,text in bar: data[ 'text' ][idx] = keyword_processor.replace_keywords(text) # 4. 结果 data |
可以看到处理7%的数据用了7分钟,明显比replace快了一倍
看下替换效果:
替换完后的数据:
asyncio+flashtext异步替换字符串,这老快了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import asyncio import flashtext async def replace_text(text, keyword_processor): """ 异步替换文本函数 """ replaced_text = keyword_processor.replace_keywords(text) return replaced_text async def replace_text_in_list(text_list, keyword_processor): """ 对列表中的文本进行异步替换 """ tasks = [] for text in text_list: task = asyncio.create_task(replace_text(text, keyword_processor)) tasks.append(task) replaced_text_list = await asyncio.gather( * tasks) return replaced_text_list if __name__ = = '__main__' : text_list = [ 'hello world' , 'this is a test' , 'python is awesome' ] keyword_processor = flashtext.KeywordProcessor() keyword_processor.add_keyword( 'python' , 'Java' ) keyword_processor.add_keyword( 'world' , 'universe' ) loop = asyncio.get_event_loop() replaced_text_list = loop.run_until_complete(replace_text_in_list(text_list, keyword_processor)) print (replaced_text_list) |
多思考也是一种努力,做出正确的分析和选择,因为我们的时间和精力都有限,所以把时间花在更有价值的地方。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?