目錄
前提提要
要求
思路
代碼
運作結果
分析
1)讀取檔案
2)讀取資料
3)資料整理
4)正規表達式比對外加資料去重
6)資料導出儲存
前提提要
python2.0有無法直接讀取中文路徑的問題,需要另外寫函數。python3.0在2018年的時候也無法直接讀取。
現在使用的時候,發現python3.0是可以直接讀取中文路徑的。
需要自帶或者建立幾個txt檔案,裡面最好寫幾個資料(姓名,手機号,住址)
要求
寫代碼的時候最好,自己設幾個要求,明确下目的。
- 需要讀取對應目錄路徑的所有對應檔案
- 按行讀取出每個對應txt檔案的記錄
- 使用正規表達式擷取每行的手機号
- 将手機号碼存儲到excel中
思路
1)讀取檔案
2)讀取資料
3)資料整理
4)正規表達式比對
5)資料去重
6)資料導出儲存
代碼
import glob
import re
import xlwt
filearray=[]
data=[]
phone=[]
filelocation=glob.glob(r'課堂實訓/*.txt')
print(filelocation)
for i in range(len(filelocation)):
file =open(filelocation[i])
file_data=file.readlines()
data.append(file_data)
print(data)
combine_data=sum(data,[])
print(combine_data)
for a in combine_data:
data1=re.search(r'[0-9]{11}',a)
phone.append(data1[0])
phone=list(set(phone))
print(phone)
print(len(phone))
#存到excel中
f=xlwt.Workbook('encoding=utf-8')
sheet1=f.add_sheet('sheet1',cell_overwrite_ok=True)
for i in range(len(phone)):
sheet1.write(i,0,phone[i])
f.save('phonenumber.xls')
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLzY2M4MWYzcDZhhTOiRTN5UjM5ATMmBTOmdDO1IDO1ITZjVWO2kzLchDMyIDMy8CXzV2Zh1WavwVbvNmLvR3YxUjLyM3Lc9CX6MHc0RHaiojIsJye.gif)
運作結果
編輯
會生成一個excel檔案
編輯
編輯
分析
import glob
import re
import xlwt
globe用來定位檔案,re正規表達式,xlwt用于excel
1)讀取檔案
filelocation=glob.glob(r'課堂實訓/*.txt')
指定目錄下的所有txt檔案
2)讀取資料
for i in range(len(filelocation)):
file =open(filelocation[i])
file_data=file.readlines()
data.append(file_data)
print(data)
将路徑下的txt檔案循環讀取,按序号依次讀取檔案
打開每一次循環對應的檔案
将每一次循環的txt檔案的資料按行讀取出來
使用append()方法将每一行的資料添加到data清單中
輸出一下,可以看到将幾個txt的檔案資料以字列形式存在同一個清單
3)資料整理
combine_data=sum(data,[])
清單合并成一個清單
4)正規表達式比對外加資料去重
print(combine_data)
for a in combine_data:
data1=re.search(r'[0-9]{11}',a)
phone.append(data1[0])
phone=list(set(phone))
print(phone)
print(len(phone))
set()函數:無序去重,建立一個無序不重複元素集
6)資料導出儲存
#存到excel中
f=xlwt.Workbook('encoding=utf-8')
sheet1=f.add_sheet('sheet1',cell_overwrite_ok=True)
for i in range(len(phone)):
sheet1.write(i,0,phone[i])
f.save('phonenumber.xls')
Workbook('encoding=utf-8'):設定工作簿的編碼