簡體   English   中英

在 Python 中格式化電話號碼的最佳方式是什么?

[英]What's the best way to format a phone number in Python?

如果我只有 10 個或更多數字的字符串,我如何將其格式化為電話號碼?

一些簡單的例子:

555-5555
555-555-5555
1-800-555-5555

我知道這些不是格式化它們的唯一方法,如果我自己做,我很可能會忽略這些。 是否有 python 庫或格式化電話號碼的標准方法?

對於圖書館:電話號碼( pypisource

Python 版本的 Google 通用庫,用於解析、格式化、存儲和驗證國際電話號碼。

自述文件不足,但我發現代碼有據可查。

似乎您的示例格式為除最后一位之外的三位數組,您可以編寫一個簡單的 function,使用千位分隔符並添加最后一位:

>>> def phone_format(n):                                                                                                                                  
...     return format(int(n[:-1]), ",").replace(",", "-") + n[-1]                                                                                                           
... 
>>> phone_format("5555555")
'555-5555'
>>> phone_format("5555555")
'555-5555'
>>> phone_format("5555555555")
'555-555-5555'
>>> phone_format("18005555555")
'1-800-555-5555'

這是一個改編自utdemir 的解決方案的解決方案該解決方案適用於 Python 2.6,因為“,”格式化程序是 Python 2.7 中的新功能。

def phone_format(phone_number):
    clean_phone_number = re.sub('[^0-9]+', '', phone_number)
    formatted_phone_number = re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1-", "%d" % int(clean_phone_number[:-1])) + clean_phone_number[-1]
    return formatted_phone_number

您可以使用 DataPrep 庫中的 function clean_phone clean_phone() 使用pip install dataprep安裝它。

>>> from dataprep.clean import clean_phone
>>> df = pd.DataFrame({'phone': ['5555555', '5555555555', '18005555555']})
>>> clean_phone(df, 'phone')
Phone Number Cleaning Report:                                                   
    3 values cleaned (100.0%)
Result contains 3 (100.0%) values in the correct format and 0 null values (0.0%)
         phone     phone_clean
0      5555555        555-5555
1   5555555555    555-555-5555
2  18005555555  1-800-555-5555

更詳細,一個依賴,但保證 output 對於大多數輸入是一致的,寫起來很有趣:

import re

def format_tel(tel):
    tel = tel.removeprefix("+")
    tel = tel.removeprefix("1")     # remove leading +1 or 1
    tel = re.sub("[ ()-]", '', tel) # remove space, (), -

    assert(len(tel) == 10)
    tel = f"{tel[:3]}-{tel[3:6]}-{tel[6:]}"

    return tel

Output:

>>> format_tel("1-800-628-8737")
'800-628-8737'
>>> format_tel("800-628-8737")
'800-628-8737'
>>> format_tel("18006288737")
'800-628-8737'
>>> format_tel("1800-628-8737")
'800-628-8737'
>>> format_tel("(800) 628-8737")
'800-628-8737'
>>> format_tel("(800) 6288737")
'800-628-8737'
>>> format_tel("(800)6288737")
'800-628-8737'
>>> format_tel("8006288737")
'800-628-8737'

沒有幻數; ...如果您不了解整個簡潔性:

def format_tel(tel):
    AREA_BOUNDARY = 3           # 800.6288737
    SUBSCRIBER_SPLIT = 6        # 800628.8737
    
    tel = tel.removeprefix("+")
    tel = tel.removeprefix("1")     # remove leading +1, or 1
    tel = re.sub("[ ()-]", '', tel) # remove space, (), -

    assert(len(tel) == 10)
    tel = (f"{tel[:AREA_BOUNDARY]}-"
           f"{tel[AREA_BOUNDARY:SUBSCRIBER_SPLIT]}-{tel[SUBSCRIBER_SPLIT:]}")

    return tel

一個簡單的解決方案可能是從后面開始並在四個數字后插入連字符,然后以三個為一組,直到到達字符串的開頭。 我不知道內置 function 或類似的東西。

您可能會發現這很有幫助: http://www.diveintopython3.net/regular-expressions.html#phonenumbers

如果您接受用戶輸入的電話號碼,正則表達式將很有用。 我不會使用上面鏈接中遵循的確切方法。 更簡單的事情,比如去掉數字,可能更容易而且同樣好。

此外,在數字中插入逗號是一個類似的問題,已經在其他地方有效地解決了,並且可以適應這個問題。

就我而言,我需要按國家/地區獲取“*** *** ***”之類的電話模式。

所以我在我們的項目中重新使用了phonenumbers

from phonenumbers import country_code_for_region, format_number, PhoneMetadata, PhoneNumberFormat, parse as parse_phone
import re

def get_country_phone_pattern(country_code: str):
    mobile_number_example = PhoneMetadata.metadata_for_region(country_code).mobile.example_number
    formatted_phone = format_number(parse_phone(mobile_number_example, country_code), PhoneNumberFormat.INTERNATIONAL)
    without_country_code = " ".join(formatted_phone.split()[1:])
    return re.sub("\d", "*", without_country_code)

get_country_phone_pattern("KG")  # *** *** ***

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM