Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python RE,AttributeError:';元组';对象没有属性';集团';_Python_Regex_Python 2.7 - Fatal编程技术网

Python RE,AttributeError:';元组';对象没有属性';集团';

Python RE,AttributeError:';元组';对象没有属性';集团';,python,regex,python-2.7,Python,Regex,Python 2.7,我试图使用Python2.7Regex从我正在学习的课程中提供的示例网页中检索数据。我正在尝试的代码是: email_patterns = ['(?P<lname>[\w+\.]*\w+ *)@(?P<domain> *\w+[\.\w+]*).(?P<tld>com) for pattern in email_patterns: # 'line' is a line of text in a sample web page

我试图使用Python2.7Regex从我正在学习的课程中提供的示例网页中检索数据。我正在尝试的代码是:

email_patterns = ['(?P<lname>[\w+\.]*\w+ *)@(?P<domain> *\w+[\.\w+]*).(?P<tld>com)

for pattern in email_patterns:
        # 'line' is a line of text in a sample web page
        matches = re.findall(pattern,line)
        for m in matches:
            print 'matches=', m
            email = '{}@{}.{}'.format(m.group('lname'), m.group('domain'),m.group('tld')) 
我想使用命名组,因为组的顺序可以根据我匹配的文本而改变。但是,它似乎不起作用,因为编译器不认为“m”是组对象


这里发生了什么,如何使用命名组使其正常工作?

您有两个问题。正如Ignacio所暗示的,您不应该使用正则表达式解析(X)HTML。。。正则表达式无法处理这种复杂性。另一个问题是您正在使用
findall()
而不是
finditer()
findall()
将匹配项作为列表返回。。。如果是组,它将以元组列表的形式返回

另一方面,
finditer()
返回具有
group()
方法的
MatchGroup
对象的迭代器

从python文档中获取:

re.findall(pattern,string,flags=0)返回字符串中模式的所有非重叠匹配,作为字符串列表。字符串是 从左到右扫描,并按找到的顺序返回匹配项。如果 如果模式中存在一个或多个组,则返回 组;如果模式有多个元组,这将是一个元组列表 小组。空匹配项包括在结果中,除非它们与 另一场比赛的开始

finditer(pattern,string,flags=0)返回一个迭代器 针对RE的所有非重叠匹配的MatchObject实例 字符串中的模式。字符串从左到右扫描,并匹配 按找到的顺序返回。空匹配项包含在 结果,除非他们触及另一场比赛的开始


这是另外两个问题的顶部。这可能值得一提BeautifulSoup或类似的库作为正则表达式的可能解决方案。谢谢,Michael。这很有帮助。我试试看,芬迪特。关于正则表达式在我的场景中是否合适:事实上,它们是。原因如下:这是课程作业的一部分,重点是使用Python和正则表达式。Python和正则表达式的使用是一项要求。如果我不使用它们,我就得不到学分。:-)@乌萨宾:好的。如果您对表达式有任何问题,可以找到许多正则表达式来验证(匹配)电子邮件地址。大多数人都对如何使用regex完成这样的任务进行了冗长的讨论。。。有些要点在课堂上可能是有效的杰出的谢谢你的链接。
email = '{}@{}.{}'.format(m.group('lname'), m.group('domain'), m.group('tld'))
AttributeError: 'tuple' object has no attribute 'group'.