1.替換
思路:
- 把雙引號【"】替換爲橫線【-】
-
把雙豎線【||】替換爲單個雙引號【"】
#替換
import re
from tqdm import tqdm
#清洗數據
def file_sub(old_file,new_file):
file_data = [] # 初始化
with open(old_file, "r", encoding="GB18030") as f:
print('開始替換...')
rows = f.readlines()
for line in tqdm(rows):
a = re.sub('\x00','',re.sub('\s','',line))
a = re.sub('"','-',a)
a = re.sub('\|\|','"',a)
file_data.append(a)
with open(new_file, "w", encoding="GB18030") as f: # 寫入替換好的文本
print('寫入替換文本...')
for line in tqdm(file_data):
f.write(line + '\n')
print('批量替換完成')
def main():
file_sub('work.txt','work_new.csv')
2.查看是否有串行
無報錯
#2.發現串行
#發現錯誤行
import pandas as pd
file ='work_new.csv'
dat = pd.read_table(file, sep=',',encoding = "GB18030",
dtype=str,low_memory=False,
header=None
)
#無錯誤行,導出文件
dat.to_csv('work_clean.csv',sep='|',index=False,quoting=1,encoding = 'GB18030')
#讀取錯誤行
dat = pd.read_table(file, sep=',',encoding = "GB18030",
dtype=str,skiprows=2704912, nrows=1 ,low_memory=False,
header=None
)