2013-11-20 2 views
0

나는 세 개의 열이있는 목록을처음 3 줄 문자로 텍스트 파일을 그룹화하는 방법은 무엇입니까? ID, 경도, 위도 :


내 텍스트 파일의 일부 :

AFJ.SPZ.IR.8 46.84 38.463 
AKL.SPZ.IR.11 46.691 38.399 
AKL.SPZ.IR.12 46.722 38.407 
AFJ.SPZ.IR.3 46.812 38.433 
AFJ.SPZ.IR.8 46.84 38.463 
AKL.SPZ.IR.11 46.691 38.399 
AKL.SPZ.IR.12 46.722 38.407 
AKL.SPZ.IR.13 46.654 38.404 
AKL.SPZ.IR.25 46.699 38.442 
AKL.SPZ.IR.3 46.812 38.433 
AKL.SPZ.IR.8 46.84 38.463 
ALA.SPZ.IR.3 46.812 38.433 
ANAR.BHZ.IR.8 46.84 38.463 
ANJ.SPZ.IR.13 46.654 38.404 
ANJ.SPZ.IR.18 46.662 38.399 
ANJ.SPZ.IR.3 46.812 38.433 
BST.SPZ.IR.1 46.732 38.457 
BST.SPZ.IR.10 46.707 38.448 
BST.SPZ.IR.11 46.691 38.399 
BST.SPZ.IR.12 46.722 38.407 

내가 경도에 기능을 실행할 및 ID의 위도 첫 번째 문자가 같은 문자입니다. 내 코드 :

from itertools import groupby 

with open('coors1.txt') as fin: 
    lines = (line.split() for line in fin) 
    for l in lines: 
     a=l[0].split(".") 
     for key, items in groupby(l,a): 
      print (items) 

    TypeError: 'str' object is not callable 

왜 GROUPBY하지 않습니다는 STR을 이해?

답변

0
  1. 당신은 아닌 문자열 당신은 함수로 키를 지정해야합니다 groupby
  2. 을 적용하기 전에 데이터를 정렬 할 필요가

    from itertools import groupby 
    with open('Input.txt') as fin: 
        lines = sorted([line.rstrip() for line in fin]) 
    for item, grp in groupby(lines, key = lambda x:x.split(".")[0]): 
        print item, list(grp) 
    

출력

AFJ ['AFJ.SPZ.IR.3 46.812 38.433', 'AFJ.SPZ.IR.8 46.84 38.463', 'AFJ.SPZ.IR.8 46.84 38.463'] 
AKL ['AKL.SPZ.IR.11 46.691 38.399', 'AKL.SPZ.IR.11 46.691 38.399', 'AKL.SPZ.IR.12 46.722 38.407', 'AKL.SPZ.IR.12 46.722 38.407', 'AKL.SPZ.IR.13 46.654 38.404', 'AKL.SPZ.IR.25 46.699 38.442', 'AKL.SPZ.IR.3 46.812 38.433', 'AKL.SPZ.IR.8 46.84 38.463'] 
ALA ['ALA.SPZ.IR.3 46.812 38.433'] 
ANAR ['ANAR.BHZ.IR.8 46.84 38.463'] 
ANJ ['ANJ.SPZ.IR.13 46.654 38.404', 'ANJ.SPZ.IR.18 46.662 38.399', 'ANJ.SPZ.IR.3 46.812 38.433'] 
BST ['BST.SPZ.IR.1 46.732 38.457', 'BST.SPZ.IR.10 46.707 38.448', 'BST.SPZ.IR.11 46.691 38.399', 'BST.SPZ.IR.12 46.722 38.407'] 
+0

당신은'item getter' 어디서나 : P –

+0

@kroolik 지적 해 주셔서 감사합니다 :) 나는 이제 그걸 제거했습니다 – thefourtheye

+0

@ thefourtheye 당신의 도움을 많이 주셔서 감사합니다.하지만 그룹 내 모든 두 지점 (좌표)에 제 기능을 수행하는 방법을 찾지 못했습니다. – sahar