2017-02-16 75 views
2
from mrjob.job import MRJob 
import re 

Creation_date=re.compile('CreationDate=\"[0-9]*\"[:17]') 
class Part2(MRJob): 
    def mapper(self, _, line): 
     DateOnly=Creation_date.group(0).split("=") 
     if(DateOnly > 2013): 
      yield None, 1 

    def reducer(self, key, values): 
     yield key, sum(values) 

if __name__ == '__main__': 
    Part1.run() 

我已经编写了MapReduce作业的Python代码,其中CreationDate =“2010-07-28T19:04:21.300”。我必须找到创建日期在2014-01-01或之后的所有日期。但是我遇到了一个错误。属性错误:组

回答

0

Regular expression object(的re.compile结果)没有group方法:

>>> pattern = re.compile('CreationDate="([0-9]+)"') 
>>> pattern.group 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: '_sre.SRE_Pattern' object has no attribute 'group' 

为了得到match object(其中有一个group方法),你需要搭配使用regex.search method对字符串的模式(line) (或regex.match method根据您的需要):

>>> pattern.search('CreationDate="2013"') 
<_sre.SRE_Match object at 0x7fac5c64e8a0> 
>>> pattern.search('CreationDate="2013"').group(1) # returns a string 
'2013' 

Creation_date = re.compile('CreationDate="([0-9]+)"') 

def mapper(self, _, line): 
    date_only = Creation_date.search(line), group(1) 
    if int(date_only) > 2013: 
     yield None, 1 

注意:修改了正则表达式以将数字部分捕获为一个组。并将匹配的字符串转换为int(比较字符串与数字2013没有意义,或根据Python版本提出异常)

+0

:全局名称“组”没有定义。出现此错误。如何解决这个问题?谢谢。 – Gokul

+0

@ gd16,我想你没有按照我在答案中的建议进行编码。你能显示你的更新代码吗? – falsetru

0

Creation_date只是一个正则表达式。

您需要匹配您输入的字符串后,才能调用NameError group(0)