2012-05-19 3 views
0

텍스트 파일을 구문 분석하여 DB에 삽입 할 수있을 정도로 정규화하려고하는 스크립트를 작성 중입니다. 데이터는 1 명 이상의 저자가 작성한 기사를 나타냅니다. 내가 겪고있는 문제는 고정 된 수의 저자가 없기 때문에 출력 텍스트 파일에 가변 개수의 열을 갖게된다는 것입니다. 예.Python 목록에 값 삽입하기

author1, author2, author3, this is the title of the article 
author1, author2, this is the title of the article 
author1, author2, author3, author4, this is the title of the article 

이러한 결과는 내가 출력 열 짝수가되도록 빈 열을 추가해야합니다 처음 2 개 기사, 그래서 나에게 (5)의 최대 열 번호를 제공합니다. 이 작업을 수행하는 가장 좋은 방법은 무엇입니까? 필자의 입력 텍스트는 탭으로 구분되어 있으므로 탭을 분할하여 비교적 쉽게 반복 할 수 있습니다.

+0

기사 제목이 항상 목록의 마지막 항목이라고 가정하는 것이 안전합니까? 또한 어떤 접근 방식을 시도해 보셨습니까? –

+0

가변 개수의 열과 함께 작업하지만이 작업은 수행되지 않습니다. 정해진 수의 열이 있어야합니다. 목록을 작성하고 추가하려고했지만 목록에 빈 항목을 추가하는 데 어려움이 있습니다. – aeupinhere

+0

이것은 내가 서있는 곳입니다 ... http : //pastebin.com/A2CT97s9 – aeupinhere

답변

2

이미 최대 개수의 열을 가지고 있으며 이미 목록으로 분리되어 있다고 가정하면 (목록을 자신의 목록에 넣었 음을 가정합니다.) list.insert (- 지능형리스트 사용하여 원래의 목록을 파괴하지 않는

def columnize(mylists, maxcolumns): 
    for i in mylists: 
     while len(i) < maxcolumns: 
      i.insert(-1,None) 

mylists = [["author1","author2","author3","this is the title of the article"], 
      ["author1","author2","this is the title of the article"], 
      ["author1","author2","author3","author4","this is the title of the article"]] 

columnize(mylists,5) 
print mylists 

[['author1', 'author2', 'author3', None, 'this is the title of the article'], ['author1', 'author2', None, None, 'this is the title of the article'], ['author1', 'author2', 'author3', 'author4', 'this is the title of the article']] 

대체 버전 : 1 항목) 빈 열을 추가하는

def columnize(mylists, maxcolumns): 
    return [j[:-1]+([None]*(maxcolumns-len(j)))+j[-1:] for j in mylists] 

print columnize(mylists,5) 

[['author1', 'author2', 'author3', None, 'this is the title of the article'], ['author1', 'author2', None, None, 'this is the title of the article'], ['author1', 'author2', 'author3', 'author4', 'this is the title of the article']] 
1

이 용서 내가 잘못 이해 한 경우를하지만 같은 소리 당신은 어려운 방식으로 문제에 접근하고 있습니다. 그것은 저자의 집합에 제목을 매핑하는 사전에 텍스트 파일을 변환하는 것은 매우 쉽습니다 : 다음

>>> lines = ["auth1, auth2, auth3, article1", "auth1, auth2, article2","auth1, article3"] 
>>> d = dict((x[-1], x[:-1]) for x in [line.split(', ') for line in lines]) 
>>> d 
{'article2': ['auth1', 'auth2'], 'article3': ['auth1'], 'article1': ['auth1', 'auth2', 'auth3']} 
>>> total_articles = len(d) 
>>> total_articles 
3 
>>> max_authors = max(len(val) for val in d.values()) 
>>> max_authors 
3 
>>> for k,v in d.iteritems(): 
...  print k 
...  print v + [None]*(max_authors-len(v)) 
... 
article2 
['auth1', 'auth2', None] 
article3 
['auth1', None, None] 
article1 
['auth1', 'auth2', 'auth3'] 

, 당신이 정말로 원하는 경우, 출력 할 수 있습니다 파이썬에 내장 년대 csv module를 사용하여이 데이터. 또는 필요한 SQL을 직접 출력 할 수도 있습니다.

동일한 파일을 여러 번 열어 여러 번 읽으면 메모리의 데이터에서 파생시킬 수 있습니다. 이러한 목적으로 파일을 여러 번 읽지 마십시오.