点此进入CSDN

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




python异步正则字符串替换,asyncio异步正则字符串替换re

 

自然语言处理经常使用re正则模块进行字符串替换,但是文本数量特别大的时候,需要跑很久,这就需要使用asyncio异步加速处理

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import pandas as pd
import re
import asyncio
 
data = pd.read_csv("guba_all_post_20230413.csv")
 
data.dropna(inplace=True)
 
 
 
# def replace_between_dollars(strings):
#     pattern = r'\$[^$]*\$;'
#     pattern1 = r'[^\w\s]+'
#     new_strings = []
#     for idx,text in enumerate(strings):
#         text = re.sub(pattern, '', text)
#         text = re.sub(pattern1, '', text)
#         text = re.sub(r'\s+', '', text)
#         new_strings.append(text)
         
#     return new_strings
 
# replace_between_dollars(data["text"])
 
# data["new_text"] = replace_between_dollars(data["text"])
# data[:50]
 
pattern = r'\$[^$]*\$;'
pattern1 = r'[^\w\s]+'
async def replace_between_dollars(long_string):
    text = str(long_string)
    new_strings = []
    text = re.sub(pattern, '', text)
    text = re.sub(pattern1, '', text)
    text = re.sub(r'\s+', '', text)
    text = re.sub(r'[a-zA-Z]{30,}', '', text)
    text = re.sub(r"autoimg\w+", "", text)
 
    return text
  
async def main():
    tasks = []
    for i in data["text"]:
        # print(i)
        tasks.append(asyncio.create_task(replace_between_dollars(i)))
    matches_list = await asyncio.gather(*tasks)
 
    data["new_text"] = matches_list
 
    print(matches_list[:200])
    data.to_csv("guba_all_newtext_20230413.csv",index=False)
 
 
if __name__ == '__main__':
    asyncio.run(main())

  结果:

['估值有待修复煤炭平均市盈率6倍3美元', '国产医疗器械行业发展迅速迈瑞作为的国内最大的医疗器械企业基本一枝独秀了', '今日上海现货钼价', '出消息了准备套人', '你爷爷要红了', '买个了鬼半年多了没一点长进而且还跌', '没有万手哥55过不去', '今天972抄底了感觉大盘要怕怕的明天希望你给给机会出来', '可从研究开放式基金入手如010379013626005108010341等', '明570收']

posted @   高颜值的殺生丸  阅读(38)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App

作者信息

昵称:

刘新宇

园龄:4年6个月


粉丝:1209


QQ:522414928

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