【Python 第三方库】phonenumbers

2024-01-25 00:00:00

目录:

phonenumbers 模块介绍

phonenumbers 用于解析、格式化、验证和操作国际电话号码。是 Google 的 libphonenumber 库的 Python 实现,适合需要处理国际电话号码的应用场景,如用户注册、数据清洗、短信服务和国际应用等。

安装依赖:

$ pip install phonenumbers -i https://pypi.tuna.tsinghua.edu.cn/simple

号码解析

parse() 方法可以将字符串解析为标准的 PhoneNumber 对象。

对于国际格式的号码,比如中国是 +86 开头的号码,第二个参数可以设为 None 或不写;
对于本地格式的号码,第二个参数必须写,并且需要指定国家代码,如 “CN”、”GB”、”US”。

import phonenumbers

x = phonenumbers.parse("+8618056898220")
print(f"解析结果: {x}")
#解析结果: Country Code: 86 National Number: 18056898220

y = phonenumbers.parse("18056898220", "CN")
print(f"解析结果: {y}")
# 解析结果: Country Code: 86 National Number: 18056898220

如果不知道号码的国家代码是什么,参考如下示例进行查询:

import phonenumbers

x = phonenumbers.parse("+8618056898220")

# 获取号码所属国家代码
country_code = phonenumbers.region_code_for_number(x)
print(f"国家代码: {country_code}")
# 国家代码: CN

号码格式化

import phonenumbers

x = phonenumbers.parse("+8618056898220")

print(phonenumbers.format_number(x, phonenumbers.PhoneNumberFormat.INTERNATIONAL))
# 输出: +86 180 5689 8220

print(phonenumbers.format_number(x, phonenumbers.PhoneNumberFormat.NATIONAL))
# 输出: 180 5689 8220

print(phonenumbers.format_number(x, phonenumbers.PhoneNumberFormat.E164))
# 输出: +8618056898220

print(phonenumbers.format_number(x, phonenumbers.PhoneNumberFormat.RFC3966))
# 输出: tel:+86-180-5689-8220

号码验证

验证号码的有效性和可能性是数据清洗的关键步骤。

有效性: 号码格式正确且真实存在;
可能性: 号码格式正确,不保证真实存在。

import phonenumbers

x = phonenumbers.parse("+8618056898220")

# 验证号码有效性
is_valid = phonenumbers.is_valid_number(x)
print(f"号码是否有效: {is_valid}")
# 号码是否有效: True

# 检查号码可能性
is_possible = phonenumbers.is_possible_number(x)
print(f"号码是否可能: {is_possible}")
# 号码是否可能: True

获取地理位置

from phonenumbers import geocoder, parse

# 解析一个号码
number = parse("+8618056898220")

location = geocoder.description_for_number(number, "zh")
print(f"地理位置: {location}")
# 地理位置: 安徽省马鞍山市

获取运营商信息

from phonenumbers import carrier, parse

# 解析一个号码
number = parse("+8618056898220")

operator = carrier.name_for_number(number, "zh")
print(f"运营商: {operator}")
# 运营商: 中国电信

时区查询

通过时区查询可以获知号码大概是哪个地方的。

from phonenumbers import timezone, parse

time_zones = timezone.time_zones_for_number(parse('+8618056898220'))
print(f"所属时区: {time_zones}")
# 输出: 所属时区: ('Asia/Shanghai',)

从文本中提取号码

PhoneNumberMatcher 可以从一段文本中自动查找和提取电话号码。

import phonenumbers

text = "我的工作电话是 18056898220,下班后可以打给我。"
for match in phonenumbers.PhoneNumberMatcher(text, "CN"):
    print(match.raw_string) # 18056898220

返回首页

本文总阅读量  次
皖ICP备17026209号-3
总访问量: 
总访客量: