本文通过python的phone依赖包,实现查询手机号所附带的信息,并输出到Excel或者TXT中的功能。
TXT版本为本人测试版本,比较粗糙,Excel包含了纠错功能,面向用户友好。
所有代码均在
python3.10
下完美运行。
导入相关的包
txt 版本
import phone
Excel版本
import phone
import xlsxwriter as xw
from openpyxl import load_workbook
创建结果保存文件
txt版本
file = open(r".\查询结果.txt", 'w') # change!
# 打开要查询的号段文档
f = open(r".\查询号段.txt")
file.write('手机号,所属省份,所属市区,邮编,电话区号,运营商')
file.write('\n')
Excel版本
workbook_insert = xw.Workbook('查询结果.xlsx') # 创建工作簿
worksheet1 = workbook_insert.add_worksheet("号段查询结果") # 创建子表
worksheet1.activate() # 激活表
title = ['手机号', '所属省份', '所属市区','邮编','电话区号','运营商'] # 设置表头
worksheet1.write_row('A1', title) # 从A1单元格开始写入表头
循环提取数据并保存
txt版本
list_info = ['phone','province','city','zip_code','area_code','phone_type']
while True:
# 按行读取文档
phoneNum = f.readline()
# 如果读取完了就退出
if not phoneNum:
print("all done!")
break
else:
info = phone.Phone().find(int(phoneNum)) #核心代码
for list in list_info:
file.write(info[list])
file.write('\n')
print(phoneNum,'have done')
f.close()
file.close()
print(info)
f.close()
file.close()
Excel版本
j = 2 # 从第二行开始读取写入数据
while True:
# 按行读取文档
phoneNum = sheet_raw.cell(row=j, column=1).value
if not phoneNum:
print("全部查询完毕!")
break
elif isinstance(phoneNum,int) and len(str(phoneNum))==11: #判断是否是11位纯数字号码
try:
info = phone.Phone().find(int(phoneNum)) #核心代码
insertData = [info['phone'], info['province'],
info['city'], info['zip_code'],
info['area_code'], info['phone_type']]
row = 'A' + str(j)
worksheet1.write_row(row, insertData)
print(phoneNum, ' 已查询完毕!')
except:
insertData = [phoneNum, '该号码无法查询']
row = 'A' + str(j)
worksheet1.write_row(row, insertData)
print(phoneNum,'该号码无法查询')
else:
insertData = [phoneNum,'不是手机号码,请检查']
row = 'A' + str(j)
worksheet1.write_row(row, insertData)
print('第',j,'行信息不是手机号码,请检查')
# 如果读取完了就退出
j += 1
workbook_raw.close()
workbook_insert.close() # 关闭表