python - 在Python中,如果以元组中的值开头,我还需要返回哪个值

标签 python

我有一个放在元组中的区号文件

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)

我该如何做第二部分?

最佳答案

简单(如果不一定是最高性能)的方法是单独检查每个前缀,并保留第一个匹配:

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])

关于python - 在Python中,如果以元组中的值开头,我还需要返回哪个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35043162/

相关文章:

python - 将数字限制在一个范围内

android - 在 main.py 中导入第三方 (pygoogle) 库以通过 buildozer 制作 android apk 时遇到问题

python - 使用 opencv 计算特定颜色像素的图像识别

python - 查找形状内的像素索引 : Opencv and Python

python - 使用链 EncodeError(RuntimeError('获取对象的 str 时超出最大递归深度)) 时如何解决 python Celery 错误

python - 可以重新加载导入的字典吗?

python - 通过 '-c' 选项将多行传递给 Python 解释器

python - 使用 curve_fit 限制高斯拟合

python - 从 statsmodels 调用 volution_filter 时出现类型错误

python - 使用 Python 从视频文件创建缩略图