2012-11-01 74 views
1

我有以下字符串字符串到CSV文件使用Python

string = "OGC Number | LT No | Job /n 9625878 | EPP3234 | 1206545/n" and continues on 

我試圖把它寫爲.csv文件它看起來就像這樣:

OGC Number | LT No | Job 
------------------------------ 
9625878 | EPP3234 | 1206545 
9708562 | PGP43221 | 1105482 
9887954 | BCP5466 | 1025454 
  • 其中每個字符串中的換行符是新行
  • 其中每個「|」在刺是一個新的列

我無法獲得格式。

我想我需要使用:

string.split('/n') 
string.split('|') 

感謝。

Windows 7中,Python的2.6

+0

你的程序是什麼樣的?你有什麼困難? – Gerrat

+0

根據意見更新 –

回答

0

如果您有興趣使用第三方模塊。 Prettytable是非常有用的,並有一個很好的功能來處理和打印表格數據。

1

未經測試:

text=""" 
OGC Number | LT No | Job 
------------------------------ 
9625878 | EPP3234 | 1206545 
9708562 | PGP43221 | 1105482 
9887954 | BCP5466 | 1025454""" 

import csv 
lines = text.splitlines() 
with open('outputfile.csv', 'wb') as fout: 
    csvout = csv.writer(fout) 
    csvout.writerow(lines[0]) # header 
    for row in lines[2:]: # content 
     csvout.writerow([col.strip() for col in row.split('|')]) 
0

編輯:哎呀,我錯過了你的問題!

下面的代碼將使用兩個正則表達式來進行修改。

import re 

str="""OGC Number | LT No | Job 
------------------------------ 
9625878 | EPP3234 | 1206545 
9708562 | PGP43221 | 1105482 
9887954 | BCP5466 | 1025454 
""" 
# just setup above 

# remove all lines with at least 4 dashes 
str=re.sub(r'----+\n', '', str) 

# replace all pipe symbols with their 
# surrounding spaces by single semicolons 
str=re.sub(r' +\| +', ';', str) 

print str 
+0

命名內容類型「str」並不是一個好主意...... –

相關問題