2014-01-07 46 views
0

我有一個csv文件是「名稱,地點,東西」。東西列往往有「word \ nanotherword \ nanotherword \ n」我想弄清楚如何解析出來的單行而不是單列中的多行條目。即如何用python解析csv,當一列有多行時

name, place, word

name, place, anotherword

name, place , anotherword

我敢肯定,這是簡單的,但有一個很難把握什麼,我需要做IM。

+3

你自己爲此編寫了任何代碼嗎? – Totem

+0

查看csv模塊:http://docs.python.org/2/library/csv.html – That1Guy

回答

1

沒有進入代碼,基本上你想要做的是檢查,看看是否有是你的'東西'中的任何換行符。如果有的話,你需要把它們分割成換行符。這會給你一個令牌列表('東西'中的行),因爲這實質上是一個內部循環,所以你可以使用原始的nameplace以及你的新thing_token。生成器函數非常適合這一點。

這是kroolik的答案。然而,有一個在kroolik的回答略有誤差:

如果你想要去的column_wrapper生成器,你將需要考慮的是,CSV讀者轉義反斜線在新行的事實,讓它們看起來像\\n代替\n 。另外,你需要檢查空白的'東西'。

def column_wrapper(reader): 
    for name, place, thing in reader: 
     for split_thing in thing.strip().split('\\n'): 
      if split_thing: 
       yield name, place, split_thing 

然後你就可以得到的數據是這樣的:

with open('filewithdata.csv', 'r') as csvfile: 
    reader = csv.reader(csvfile) 
    data = [[data, name, thing] for data, name, thing in column_wrapper(reader)] 

OR(無column_wrapper):

data = [] 
with open('filewithdata.csv', 'r') as csvfile: 
    reader = csv.reader(csvfile) 
    for row in reader: 
     name, place, thing = tuple(row) 
     if '\\n' in thing: 
      for item in thing.split('\\n'): 
       if item != '\n': 
        data.append([name, place, item)] 
作爲發電機更通用和Python的,我建議使用 column_wrapper

一定要將import csv添加到文件的頂部(儘管我確定您已經知道了)。希望有所幫助!

2

包裝你的CSV讀卡器配合本column_wrapper

def column_wrapper(reader): 
    for name, place, thing in reader: 
     for split_thing in thing.strip().split('\n'): 
      yield name, place, split_thing 

你會生金。

0

你總是可以通過線

#! /usr/bin/env python2.7.2 
file = open("demo.csv", "r+"); 
for line in file: 
    line = line.replace(",", " ") 
    words = line.split() 
    print(words[0]) 
    print(words[1]) 
    print(words[2]) 
file.close() 

假設該文件內容的文件讀取的行

name1,place1,word1 
name2,place2,anotherword2 
name3,place3,anotherword3