如何改善正则表达式以提取电话号码?

时间:2017-12-12 21:42:46

标签: python regex pandas web-scraping

我正在尝试使用正则表达式从网络链接中提取电话号码。我面临的问题是不需要的ID和网页的其他元素。如果有人可以提出一些改进,那将非常有帮助。下面是我在Python中使用的代码和正则表达式

from urllib2 import urlopen as uReq
uClient = uReq(url)
page_html = uClient.read()
print re.findall(r"(\(?\d{3}\D{0,3}\d{3}\D{0,3}\d{4}).*?",page_html)

现在,对于大多数网站而言,脚本获取一些页面元素值,有时准确。请在表达中建议一些修改

re.findall(r"(\(?\d{3}\D{0,3}\d{3}\D{0,3}\d{4}).*?",page_html)

对于不同的网址

,我的输出如下所示
http://www.fraitagengineering.com/index.html
['(877) 424-4752']
http://hunterhawk.com/
['1481240672', '1481240643', '1479852632', '1478013441', '1481054486', '1481054560', '1481054598', '1481054588', '1476820246', '1481054521', '1481054540', '1476819829', '1481240830', '1479855986', '1479855990', '1479855994', '1479855895', '1476819760', '1476741750', '1476741750', '1476820517', '1479862863', '1476982247', '1481058326', '1481240672', '1481240830', '1513106590', '1481240643', '1479855986', '1479855990', '1479855994', '1479855895', '1479852632', '1478013441', '1715282331', '1041873852', '1736722557', '1525761106', '1481054486', '1476819760', '1481054560', '1476741750', '1481054598', '1476741750', '1481054588', '1476820246', '1481054521', '1476820517', '1479862863', '1481054540', '1476982247', '1476819829', '1481058326', '(925) 798-4950', '2093796260']
http://www.lbjewelrydesign.com/
['213-629-1823', '213-629-1823']

我只想要(000) 000-0000 (not that I have added space after parenthesis),(000)-000-0000 or 000-000-0000`格式的电话号码。任何建议赞赏。请注意,我已经提到过此链接:Find phone numbers in python script

我需要根据我的特定需求改进正则表达式。

2 个答案:

答案 0 :(得分:1)

如果只能搜索网页的纯文本,则可以避免在id,其他属性或HTML标记内部进行搜索。您可以通过BeautifulSoup HTML parser处理网页内容来实现:

from urllib2 import urlopen as uReq

from bs4 import BeautifulSoup

page_text = BeautifulSoup(uReq(url), "html.parser").get_text()

然后,正如杰克在评论中提到的那样,你可以使你的正则表达更可靠:

答案 1 :(得分:1)

以下正则表达式可用于匹配您提供的样本和其他类似的数字:

(\([0-9]{3}\)[\s-]?|[0-9]{3}-)[0-9]{3}-[0-9]{4}

以下示例脚本可用于测试除正则表达式之外的正面和负面情况:

import re

positiveExamples = [
    '(000) 000-0000',
    '(000)-000-0000',
    '(000)000-0000',
    '000-000-0000'
]
negativeExamples = [
    '000 000-0000',
    '000-000 0000',
    '000 000 0000',
    '000000-0000',
    '000-0000000',
    '0000000000'
]

reObj = re.compile(r"(\([0-9]{3}\)[\s-]?|[0-9]{3}-)[0-9]{3}-[0-9]{4}")

for example in positiveExamples:
    print 'Asserting positive example: %s' % example
    assert reObj.match(example)

for example in negativeExamples:
    print 'Asserting negative example: %s' % example
    assert reObj.match(example) == None