python 去除特定字符 轉(zhuǎn)csv

整體思路

1. 去空去重 去掉不想要的字符串

2. 拆成兩列一維數(shù)組

3. 合并成一 列二維數(shù)組

4. 二維數(shù)組轉(zhuǎn)csv

```python

# -*- coding: utf-8 -*-

import os

import xlwt

a = os.getcwd() #獲取當前目錄

print (a) #打印當前目錄

os.chdir('D:\Work\Tool\Log-data\RLog') #定位到新的目錄,請根據(jù)你自己文件的位置做相應(yīng)的修改

a = os.getcwd() #獲取定位之后的目錄

print(a) #打印定位之后的目錄

#讀取目標txt文件里的內(nèi)容,并且打印出來顯示

with open('LogText.txt','r') as raw:

? ? for line in raw:

? ? ? ? print (line)

? ? # 去掉txt里面的空白行,除特定格式外的字符串 并保存到新的文件中

with open('LogText.txt', 'r', encoding='utf-8') as fr, open('output.txt', 'w', encoding='utf-8') as fd:

? ? for text in fr.readlines():

? ? ? ? if text.split() and "channel: " in text:

? ? ? ? ? ? fd.write(text)

with open('output.txt','r') as raw:

? ? for line in raw:

? ? ? ? print (line)

print('success')

#創(chuàng)建一個workbook對象,相當于創(chuàng)建一個Excel文件

book = xlwt.Workbook(encoding='utf-8',style_compression=0)

#wb = openpyxl.Workbook(encoding='utf-8',style_compression=0)? # 打開一個將寫的文件

#ws=wb.active

# 創(chuàng)建一個sheet對象,一個sheet對象對應(yīng)Excel文件中的一張表格。

sheet = book.add_sheet('Output', cell_overwrite_ok=True)

header=['channel','value']

header1=['channel','value']

#對文本內(nèi)容進行多次切片得到想要的部分

n=1

? ? # 3:遍歷列表,將每一行的數(shù)據(jù)寫入csv

# 最后,將以上操作保存到指定的Excel文件中

a1=[]

b1=[]

c=[]

d=[]

e=[]

with open('output.txt', 'r+') as fd:

? ? for text in fd.readlines():

? ? ? ? x = text.split(':')[1]

? ? ? ? y = text.split(':')[2]

? ? ? ? a=x.split('value')[0]

? ? ? ? b=y.split('\n')[0]

? ? ? ? #b=text.split(':')[2]

? ? ? ? # print (x.split('value'))

? ? ? ? # print (y.split('\n'))

? ? ? ? d=a+b

? ? ? ? a1.append(a)

? ? ? ? b1.append(b)

? ? ? ? #d.append(d)

? ? ? ? f=x.split('value')[0]

? ? ? ? g=y.split('\n')[0]

? ? ? ? d=x.split('value')[0]+','+y.split('\n')[0]

? ? ? ? new_d=d.split(",");

? ? ? ? # a1.append(a)

? ? ? ? # b1.append(b)

? ? ? ? #e=[list(t) for t in zip(f,g)]

? ? ? ? e.append(new_d)#[[],[],[]]

? ? ? ? #

? ? ? ? #? csvs = "".join("(" + x.split('value')[0] + "," + y.split('\n')[0] + ")," + '\n')

for i in range( max ( len( a1 ), len( b1 ) ) ):

? ? if a1:

? ? ? ? c.append( a1.pop() )

? ? ? ? if b1:

? ? ? ? ? ? c.append( b1.pop() )#[,,,,,,,,,]

"""

Yongqiang Cheng

"""

polylines_list = c

interval = 2

polyline_set = []

if (len(polylines_list) % 2 == 0):

? ? for idx in range(0, len(polylines_list), 2):

? ? ? ? polyline_set.append([polylines_list[idx], polylines_list[idx + 1]])

else:

? ? print("IndexError: list index out of range.")

print(polyline_set)

# coding:utf-8

import csv

f = open('222.csv','w',newline='')

writer = csv.writer(f)

writer.writerow(header)

for i in polyline_set:

? ? writer.writerow(i)

f.close()

```

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容