python - 使用 Python 规范化电话号码

标签 python

我对 python 非常陌生。我经常收到包含电话号码的各种格式的文本文件。我正在尝试创建一个 python 脚本,它接受这个文本文件并将它们规范化为我可以使用的格式。

我正在尝试删除所有符号和空格,只保留数字。以及在开头添加 +1 并在末尾添加逗号 (,)。

import re

with open("test_numbers.txt") as file:
    dirty = file.read()
    clean = re.sub(r'[^0-9]', '', dirty)

print clean

我正在尝试使用正则表达式,但它会将所有内容放在一行中。也许我做错了。我还没有找到将 +1 添加到数字开头或在末尾添加逗号的方法。非常感谢任何建议。

最佳答案

这可能对您有帮助:

import re

with open('test_numbers.txt') as f:
    dirty = f.readlines()

clean = []
for l in dirty:
    clean.apped('+1{},\n'.format(re.sub(r'[^0-9]', '', l)))

clean 将是一个以 +1 开头,以 , 结尾的行列表。然后您可以将其保存到文本文件中:

with open('formatted_numbers.txt', 'w') as f:
    f.writelines(clean)

您还可以使用列表推导式使用单行代码:

clean = ['+1{},\n'.format(re.sub(r'[^0-9]', '', l)) for l in dirty]

关于python - 使用 Python 规范化电话号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50978414/

相关文章:

python - efrc 给出错误 length-1 数组可以转换为 python

python - 使用 Keras、Python 纠正 CNN、基于 LSTM 的分类器的输入维度

python - docopt boolean arg python

python - 为什么 float64 允许 NA,而 int32 不允许?

python - 理解张量的秩和行为

python - 在 Tkinter 文本小部件中粘贴

python - 找到新的导出目的地 : Data science - groupby and isin

python - 将 matplotlib 图形 Canvas 图像插入 QTextDocument

python - 根据 Pandas 列中的多个值从 DataFrame 中选择行

python - Bokeh 对数轴格式为十进制