【问题标题】:How to obtain all the phone numbers in each row of a df, using phonenumbers Python Library?如何使用 phonenumbers Python 库获取 df 每一行中的所有电话号码?
【发布时间】:2020-12-07 17:41:24
【问题描述】:

我想使用 Python 的 phonenumber 库在数据框中的 text 列的每一行中创建一个包含所有有效电话号码的列。

complains = ['If you validate your data, your confirmation number is 1-23-456-789, for a teacher you will be debited on the 3rd of each month 41.99, you will pay for the remaining 3 services offered:n/a',
             'EMAIL VERIFYED, 12345 1st STUDENT 400 88888 2nd STUDENT 166.93 Your request has been submitted and your confirmation number is 1-234-567-777 speed is increased to 250MB $80.99 BILLING CYCLE 18',
             'ADJUSTMENT FROM NOVEMBER TO MAY $80.99 Appointment for equipment change 7878940142']

complainsdf = pd.DataFrame(complains, index =['1', '2', '3'], columns =['text'])

我尝试了下面的代码。但我没有得到我预期的结果。

complainsdf['tel'] = complainsdf.apply(lambda row: 
    phonenumbers.PhoneNumberMatcher(row['text'], "US"), axis=1)

complainsdf['tel'][0] 给我以下输出: <phonenumbers.phonenumbermatcher.PhoneNumberMatcher at 0x2623ebfddf0> 而不是预期的电话号码。

【问题讨论】:

    标签: python pandas python-phonenumber


    【解决方案1】:

    tel 列的每行可以包含多个电话号码。它们存储为phonenumbers.PhoneNumberMatcher 类型的对象。

    要提取原始电话号码,您必须使用循环遍历对象。例如,您可以这样做:

    def get_phone_numbers(x):
        # Extract the phone numbers from the text
        nums = phonenumbers.PhoneNumberMatcher(x, "US")
        # Convert the phone number format
        return [phonenumbers.format_number(num.number, phonenumbers.PhoneNumberFormat.E164) for num in nums]
    
    complainsdf['tel'] = complainsdf['text'].apply(get_phone_numbers)
    complainsdf
    

                                                     text   tel
    1   If you validate your data, your confirmation n...   []
    2   EMAIL VERIFYED, 12345 1st STUDENT 400 88888 2n...   []
    3   ADJUSTMENT FROM NOVEMBER TO MAY $80.99 Appoint...   [+17878940142]
    

    我在documentation 中找到了用PhoneNumberFormat.E164 转换格式的方法。也许您必须根据自己的情况对其进行调整。

    【讨论】:

    • 感谢您的回复。有用。但是,如果任何用户提出不需要两个不同步骤的答案,我会等待。
    • 好的,我将这两个步骤合二为一。我编辑了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 2020-03-12
    • 2023-03-22
    • 1970-01-01
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多