我正在编写一个 python MapReduce 字数统计程序。问题是数据中有很多非字母字符,我发现这篇文章Stripping everything but alphanumeric chars from a string in 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
恐怕我不确定如何使用库 re
甚至是正则表达式。我不确定如何将正则表达式模式正确应用于传入的字符串(书的行) v
以检索没有任何非字母数字字符的新行。
建议?
最佳答案
使用 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'
或者,如果您只想删除某组字符(因为在您的输入中可以使用撇号...)
regex = re.compile('[,\.!?]') #etc.
关于Python,从字符串中删除所有非字母字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22520932/