我是python的新手并尝试处理大数据代码,但无法理解表达式 re.compile(r" [\ w'] +")意思。任何人都对此有任何想法?
这是我正在使用的代码。
from mrjob.job import MRJob
import re
WORD_REGEXP = re.compile(r"[\w']+")
class MRWordFrequencyCount(MRJob):
def mapper(self, _, line):
words = WORD_REGEXP.findall(line)
for word in words:
yield word.lower(), 1
def reducer(self, key, values):
yield key, sum(values)
if __name__ == '__main__':
MRWordFrequencyCount.run()
答案 0 :(得分:3)
这是一个经过编译以便更快重用的正则表达式(在此问题中解释:Is it worth using re.compile)。命令re.compile在Python docs中解释。
关于特定的正则表达式,这将搜索具有字母数字(即\w
部分)或撇号(也在那些方括号中)为1或更长的组。请注意,空格不匹配,因此,一般来说,这会将一行划分为单词。
请参阅Python特定的正则表达式测试程序中的the query进行试用,或在regex101上查看任何正则表达式的解释。
在短语How's it going $#
中,这将匹配三个匹配:How's
,it
,going
但不匹配符号组。
有许多教程甚至是一些游戏,但你可以从regexone开始,通过尝试一些来更好地理解它。
答案 1 :(得分:1)
在 re.compile('\W')
的帮助下,我们可以从字符串中删除特殊字符。
示例:
str = 'how many $ amount spend for Car??'
pattern = re.compile('\W')
x = re.sub(pattern, ' ', str)
print(x)
结果:
<块引用>购买汽车的金额
注意:特殊章程"$"和"?"从字符串中删除。