2017-05-07 7 views
0

csv 파일을 구문 분석해야합니다.csv 다른 열 값에 해당하는 열 읽기

입력 : 파일 + 이름

Index | writer | year | words 
    0  | Philip | 1994 | this is first row 
    1  | Heinz | 2000 | python is wonderful (new line) second line 
    2  | Thomas | 1993 | i don't like this 
    3  | Heinz | 1898 | this is another row 
    .  |  .  | . |  . 
    .  |  .  | . |  . 
    N  | Fritz | 2014 | i hate man united 

출력 : 대응하는 모든 단어의 목록을 무엇 내가 시도

l = ['python is wonderful second line', 'this is another row'] 

이름을 지정합니다?

import csv 
import sys 

class artist: 
    def __init__(self, name, file): 
     self.file = file 
     self.name = name 
     self.list = [] 

    def extractText(self): 
     with open(self.file, 'rb') as f: 
      reader = csv.reader(f) 
      temp = list(reader) 
     k = len(temp) 
     for i in range(1, k): 
      s = temp[i] 
      if s[1] == self.name: 
       self.list.append(str(s[3])) 


if __name__ == '__main__': 
    # arguements 
    inputFile = str(sys.argv[1]) 
    Heinz = artist('Heinz', inputFile) 
    Heinz.extractText() 
    print(Heinz.list) 

출력은 다음과 같습니다 루프가 매우 느린로 나는 단어 하나 개 이상의 라인을 포함하는 셀에 대한 \r\n 제거하려면 어떻게

["python is wonderful\r\nsecond line", 'this is another row'] 

등을 개선 할 수 있을까?

답변

1

파일을 읽는 동안 구문 분석을 수행 한 다음 원하지 않는 캐리지 리턴과 줄 바꿈 문자가 있으면 제거해야하므로이 작업은 적어도 빠릅니다. 내가 원하는 것이 아니다

import re 

def extractText(self): 
    RE_WHITESPACE = re.compile(r'[ \t\r\n]+') 
    with open(self.file, 'rU') as f: 
     reader = csv.reader(f) 

     # skip the first line 
     next(reader) 

     # put all of the words into a list if the artist matches 
     self.list = [RE_WHITESPACE.sub(' ', s[3]) 
        for s in reader if s[1] == self.name] 
1

당신은 단순히 목록을 가져올 수 팬더을 사용할 수

import pandas 
df = pandas.read_csv('test1.csv') 
index = df[df['writer'] == "Heinz"].index.tolist() # get the specific name's index 
l = list() 
for i in index: 
    l.append(df.iloc[i, 3].replace('\n','')) # get the cell and strip new line '\n', append to list. 
l 

출력 :

['python is wonderful second line', 'this is another row'] 
+0

:

with open(self.file) as csv_fh: for n in csv.reader(csv_fh): if n[1] == self.name: self.list.append(n[3].replace('\r\n', ' ') 

+0

@TonyTannous 특정 작성자의 답변을 업데이트했습니다. –

1

s[3]에 줄 바꿈을 제거하기 : 나는 ' '.join(s[3].splitlines())을 건의 할 것입니다. "".splitlines에 대한 문서를 참조하십시오. "".translate도 참조하십시오.

루프를 개선 :

def extractText(self): 
    with open(self.file, 'rb') as f: 
     for s in csv.reader(f): 
      s = temp[i] 
      if s[1] == self.name: 
       self.list.append(str(s[3])) 

이 데이터를 통해 하나 개의 패스를 저장합니다.

그러나 @ Tiny.D의 조언을 고려하고 팬더에게 시험해보십시오.

+0

하지만 줄을 제거하기 전에 각 개체에 전체 텍스트를 저장해야합니다. 내가하지 않니? 나는 그들 모두가 아닌 특정한 단어가 필요하다. –

+0

원래 코드는 모든 파일 내용을'temp = list (reader)'에있는 메모리에 복사합니다; 여기에서 각 라인은 s [1] == self.name; 대부분의 행은 버려집니다. – tiwo

0

는 정규 표현식을 사용할 수 있으며, 물건을 조금 속도 루프의 이해를 시도하기 위해 여러 공백을 축소하려면. 특정 작가/예술가의 말이 필요합니다. 모든 단어가 아닙니다.