我正在编写一个python MapReduce字数统计程序.问题是数据中散布着许多非字母字符,我发现这篇文章从Python中的字符串中删除除字母数字字符之外的所有字符,这显示了使用正则表达式的一个很好的解决方案,但我不知道如何实现它
def mapfn(k, v):
print v
import re, string
pattern = re.compile('[\W_]+')
v = pattern.match(v)
print v
for w in v.split():
yield w, 1
Run Code Online (Sandbox Code Playgroud)
我担心我不确定如何使用库re甚至正则表达式.我不确定如何正确地将正则表达式模式应用于传入的字符串(书的行)v以检索没有任何非字母数字字符的新行.
建议?
lim*_*to0 91
使用 re.sub
import re
regex = re.compile('[^a-zA-Z]')
#First parameter is the replacement, second parameter is your input string
regex.sub('', 'ab3d*E')
#Out: 'abdE'
Run Code Online (Sandbox Code Playgroud)
或者,如果您只想删除某组字符(因为撇号在您的输入中可能没问题......)
regex = re.compile('[,\.!?]') #etc.
Run Code Online (Sandbox Code Playgroud)
Tad*_*Tad 37
如果您不想使用正则表达式,您可以尝试
''.join([i for i in s if i.isalpha()])
Run Code Online (Sandbox Code Playgroud)
Kev*_*vin 25
您可以使用re.sub()函数删除这些字符:
>>> import re
>>> re.sub("[^a-zA-Z]+", "", "ABC12abc345def")
'ABCabcdef'
Run Code Online (Sandbox Code Playgroud)
re.sub(MATCH PATTERN,REPLACE STRING,STRING TO SEARCH)
"[^a-zA-Z]+" - 寻找不是a-zA-z的任何字符组."" - 用""替换匹配的字符Don*_*Don 17
尝试:
s = filter(str.isalnum, s)
Run Code Online (Sandbox Code Playgroud)
最快的方法是正则表达式
#Try with regex first
t0 = timeit.timeit("""
s = r2.sub('', st)
""", setup = """
import re
r2 = re.compile(r'[^a-zA-Z0-9]', re.MULTILINE)
st = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()-=_+'
""", number = 1000000)
print(t0)
#Try with join method on filter
t0 = timeit.timeit("""
s = ''.join(filter(str.isalnum, st))
""", setup = """
st = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()-=_+'
""",
number = 1000000)
print(t0)
#Try with only join
t0 = timeit.timeit("""
s = ''.join(c for c in st if c.isalnum())
""", setup = """
st = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()-=_+'
""", number = 1000000)
print(t0)
2.6002226710006653 Method 1 Regex
5.739747313000407 Method 2 Filter + Join
6.540099570000166 Method 3 Join
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
130625 次 |
| 最近记录: |