2011-12-02 2 views
1

... 나는 나 혼자 BBB에서 값을 추출과 같은 목록에 추가 할 수없는 생각이파이썬에서 파일의 특정 값 집합을 추출하는 방법은 무엇입니까? 내가 여기에 논리와 붙어

AAA 
+-------------+------------------+ 
|   ID |   count | 
+-------------+------------------+ 
|   3 |    1445 | 
|   4 |    105 | 
|   9 |    160 | 
|   10 |    30 | 
+-------------+------------------+ 
BBB 
+-------------+------------------+ 
|   ID |   count | 
+-------------+------------------+ 
|   3 |    1445 | 
|   4 |    105 | 
|   9 |    160 | 
|   10 |    30 | 
+-------------+------------------+ 
CCC 
+-------------+------------------+ 
|   ID |   count | 
+-------------+------------------+ 
|   3 |    1445 | 
|   4 |    105 | 
|   9 |    160 | 
|   10 |    30 | 
+-------------+------------------+ 

과 같은 텍스트 파일에서 일부 값을 추출해야

f = open(sys.argv[1], "r") 
text = f.readlines() 
B_Values = [] 
for i in text: 
    if i.startswith("BBB"):(Example) 
     B_Values.append("only values of BBB") 
    if i.startswith("CCC"): 
     break 

print B_Values 

이것

['|   3 |    1445 |','|   4 |    105 |','|   9 |    160 |','|   10 |    30 |'] 
+0

숙제입니까? –

답변

3
d = {} 
with open(sys.argv[1]) as f: 
    for line in f: 
     if line[0].isalpha(): # is first character in the line a letter? 
      curr = d.setdefault(line.strip(), []) 
     elif filter(str.isdigit, line): # is there any digit in the line? 
      curr.append(line.strip()) 

결과해야 파일 d는 지금 :

{'AAA': ['|   3 |    1445 |', 
     '|   4 |    105 |', 
     '|   9 |    160 |', 
     '|   10 |    30 |'], 
'BBB': ['|   3 |    1445 |', 
     '|   4 |    105 |', 
     '|   9 |    160 |', 
     '|   10 |    30 |'], 
'CCC': ['|   3 |    1445 |', 
     '|   4 |    105 |', 
     '|   9 |    160 |', 
     '|   10 |    30 |']} 

귀하의 B_valuesd['BBB']

0

당신은 B 그룹이 시작되었을 때 추적 을 bstarted 상태 플래그를 사용할 수 있습니다. B 그룹을 스캔 한 후 세 개의 머리글 행과 한 바닥 글 행을 삭제하십시오.

B_Values = [] 
bstarted = False 
for i in text: 
    if i.startswith("BBB"): 
     bstarted = True 
    elif i.startswith("CCC"): 
     bstarted = False 
     break 
    elif bstarted: 
     B_Values.append(i) 

del B_Values[:3] # get rid of the header 
del B_Values[-1] # get rid of the footer 
print B_Values 
0

이미 읽은 행을 반복하지 마십시오. 당신이 무엇인지 확인하기 위해 다음 라인을 읽고 검사 할 때마다의 readline 전화 :

f = open(sys.argv[1], "r") 
B_Values = [] 
while i != "": 
    i = f.readline() 
    if i.startswith("BBB"): #(Example) 
     for temp in range(3): 
      f.skipline() #Skip the 3 lines of table headers 
     i = f.readline() 
     while i != "+-------------+------------------+" and i !="": 
      #While we've not reached the table footer 
      B_Values.append(i) 
      i = f.readline() 
     break 

#Although not necessary, you'd better put a close function there, too. 
f.close() 

print B_Values 

편집 : @eumiro의 방법은 나보다 더 유연하다. 이후 모든 섹션에서 모든 값을 읽습니다. 위 예제에서 isalpha 테스트를 구현하여 모든 값을 읽을 수는 있지만 그의 메소드는 더 읽기 쉽습니다.

관련 문제