使用Python中的正则表达式进行搜索和替换

Jos*_*osh 4 python regex

我有一个充满推文的日志文件.每条推文都在自己的行上,这样我就可以轻松地遍历文件了.

一个示例推文就像这样:

@ sample This is a sample string $ 1.00 # sample
Run Code Online (Sandbox Code Playgroud)

我想通过删除特殊字符和下面的字母数字字符之间的空格来清除它."@ s","$ 1","#s"

所以它看起来像这样:

@sample This is a sample string $1.00 #sample
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用正则表达式来匹配这些实例,因为它们可以变量,但我不确定如何执行此操作.

我一直在使用re.sub()和re.search()来查找实例,但我正在努力弄清楚如何在保持字符串完整的同时删除空格.

这是我到目前为止的代码:

#!/usr/bin/python

import csv
import re
import sys
import pdb
import urllib

f=open('output.csv', 'w')

with open('retweet.csv', 'rb') as inputfile:
    read=csv.reader(inputfile, delimiter=',')
    for row in read:
        a = row[0]
        matchObj = re.search("\W\s\w", a)
        print matchObj.group()

f.close()
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

Ash*_*ary 5

这样的东西使用re.sub:

>>> import re
>>> strs = "@ sample This is a sample string $ 1.00 # sample"
>>> re.sub(r'([@#$])(\s+)([a-z0-9])', r'\1\3', strs, flags=re.I)
'@sample This is a sample string $1.00 #sample'
Run Code Online (Sandbox Code Playgroud)