繼我之前的question,因爲我無法得到滿意的答案。現在我有這樣的數據,不知道它究竟是列表(可能)到csv文件的字符串python
["'A','B','C'"]["'a1,a2','b1','c1'"]["'a2,a4','b3','ct'"]
我想我的最終輸出被寫入到一個CSV文件如下圖所示。我怎樣才能做到這一點?
A ,B ,C
a1,a2 ,b1 ,c1
a2,a4 ,b3 ,ct
繼我之前的question,因爲我無法得到滿意的答案。現在我有這樣的數據,不知道它究竟是列表(可能)到csv文件的字符串python
["'A','B','C'"]["'a1,a2','b1','c1'"]["'a2,a4','b3','ct'"]
我想我的最終輸出被寫入到一個CSV文件如下圖所示。我怎樣才能做到這一點?
A ,B ,C
a1,a2 ,b1 ,c1
a2,a4 ,b3 ,ct
假設[ 「 'A', 'B', 'C'」] [ 「 'A1,A2', 'B1', 'C1'」] [「 'A2,A4',」 B3' ,‘CT’「]是一個長的字符串作爲原來的職位似乎暗示,即:
"""["'A','B','C'"]["'a1,a2','b1','c1'"]["'a2,a4','b3','ct'"]"""
然後將下面的代碼應工作:
# ORIGINAL STRING
s = """["'A','B','C'"]["'a1,a2','b1','c1'"]["'a2,a4','b3','ct'"]"""
# GET RID OF UNNECESSARY CHARACTERS FOR OUR CSV
s = s.replace("][", "--") # temporary chars to help split into lines later on
s = s.replace("[", "")
s = s.replace("]", "")
s = s.replace("\'", "")
s = s.replace("\"", "")
# SPLIT UP INTO A LIST OF LINES OF TEXT
lines = s.split("--")
# WRITE EACH LINE IN TURN TO A CSV FILE
with open("myFile.csv", mode = "w") as textFile:
# mode = w to override any other contents of an existing file, or
# create a new one.
# mode = a To append to an exising file
for line in lines:
textFile.write(line + str("\n"))
的另一種方式,再次假定數據被編碼爲一個長字符串:
import ast
# ORIGINAL STRING
s = """["'A','B','C'"]["'a1,a2','b1','c1'"]["'a2,a4','b3','ct'"]"""
# PARSE INTO A LIST OF LISTS WITH STRING ELEMENTS
s2 = s.replace("][", "],[")
s2 = ast.literal_eval(s2)
s2 = [ast.literal_eval(s2[x][0]) for x in range(len(s2))]
# WRITE EACH LIST AS A LINE IN THE CSV FILE
with open("myFile.csv", mode = "w") as textFile:
# mode = w to override any other contents of an existing file, or
# create a new one.
# mode = a To append to an exising file
for i in range(len(s2)):
line = ",".join(s2[i])
textFile.write(line + str("\n"))
由於給定的輸入不會被任何內置的數據結構接受,因此您需要將其轉換爲字符串或列表列表。在下面假設你的輸入是一個字符串。另外,您可以按照您的要求修改格式。
#!/usr/bin/python
from ast import literal_eval
def csv(li):
file_handle = open("test.csv", "w")
#stripping the outer double_quotes and splitting the list by commas
for outer in li:
temp = outer[0].strip("'")
temp = temp.split("',")
value = ""
#bulding a formatted string(change this as per your requirement
for inner in temp:
value += '{0: <10}'.format(inner.strip("'")) + '{0: >10}'.format(",")
value = value.strip(", ")
#writing the built string into the file
file_handle.write(value + "\n")
file_handle.close()
#assuming your input as string
def main():
li_str = """["'A','B','C'"]["'a1,a2','b1','c1'"]["'a2,a4','b3','ct'"]"""
li = []
start_pos, end_pos = 0, -1
#break each into a new list and appending it to li
while(start_pos != -1):
start_pos = li_str.find("[", end_pos+1)
if start_pos == -1:
break
end_pos = li_str.find("]", start_pos+1)
li.append(literal_eval(li_str[start_pos:end_pos+1]))
#li now conatins a list of lists i.e. same as the input
csv(li)
if __name__=="__main__":
main()
嘗試設置等於'[ 「 'A', 'B', 'C'」] [ 「 'A1,A2', 'B1', 'C1'」]的值,當我得到錯誤[''a2,a4','b3','ct'「]'你的意思是 - >'['A','B','C'] ['a1,a2','b1',' c1'] ['a2,a4','b3','ct']'? – Jay 2014-11-24 06:49:41
@Jay號它有單引號和雙引號。 – abn 2014-11-24 06:51:02
作爲一個字符串?例如 - >''[''A','B','C'「] [」'a1,a2','b1','c1'「] [」'a2,a4','b3', 'ct'「]」'?因爲你不能設置一個變量,即'a = ['''A','B','C'「] [」'a1,a2','b1','c1'「] [」'a2,a4 ','b3','ct'「]' – Jay 2014-11-24 06:52:29