我有一个区域代码文件,我放入元组
for line1 in area_codes_file.readlines():
if area_code_extract.search(line1):
area_codes.append(area_code_extract.search(line1).group())
area_codes = tuple(area_codes)
和我在Python中读到的文件中充满了电话号码。 如果电话号码以元组中的某个区号开头,我需要做的事情: 1是保持号码 2是要知道哪个区号与之匹配,需要将区号放在括号中。
到目前为止,我只能做1:
for line in txt.readlines():
is_number = phonenumbers.parse(line,"GB")
if phonenumbers.is_valid_number(is_number):
if line.startswith(area_codes):
print (line)
我该如何处理第二部分?
答案 0 :(得分:1)
简单(如果不一定是最高性能)方法是单独检查每个前缀,并保持第一个匹配:
for line in txt:
is_number = phonenumbers.parse(line,"GB")
if phonenumbers.is_valid_number(is_number):
if line.startswith(area_codes):
print(line, next(filter(line.startswith, area_codes)))
由于我们知道filter(line.startswith, area_codes)
只会获得一次点击,我们只需使用next
来点击。
注意:在Python 2上,您应该使用from future_builtins import filter
启动文件以获取基于filter
的生成器(当您获得匹配时,也可以通过停止搜索来节省工作量)。 Python 3的filter
已经表现得像这样。
为了获得更高的性能,同时测试所有前缀并确定使用regular expressions命中的值的方法是:
import re
# Function that will match any of the given prefixes returning a match obj on hit
area_code_matcher = re.compile(r'|'.join(map(re.escape, area_codes))).match
for line in txt:
is_number = phonenumbers.parse(line,"GB")
if phonenumbers.is_valid_number(is_number):
# Returns None on miss, match object on hit
m = area_code_matcher(line)
if m is not None:
# Whatever matched is in the 0th grouping
print(line, m.group())
最后,如果区号具有固定长度,您可以使用最后一种方法。您可以直接切片,而不是使用startswith
;你知道这个命中因为你把它自己切掉了:
# If there are a lot of area codes, using a set/frozenset will allow much faster lookup
area_codes_set = frozenset(area_codes)
for line in txt:
is_number = phonenumbers.parse(line,"GB")
if phonenumbers.is_valid_number(is_number):
# Assuming lines that match always start with ###
if line[:3] in area_codes_set:
print(line, line[:3])