2011-11-09 2 views
1

현재 처리 중이며 this .txt file의 정보를 구문 분석하려고합니다. 파일은 탭으로 구분됩니다. 사전 값으로 기본 16 값 (예 : 000000)을 구문 분석하고 사전 값으로 회사 이름 (예 : Xerox Corporation)을 찾으려고합니다. 예를 들어, 사전에서 키 000001을 조회하면 Xerox Corporation이 각각의 값으로 반환됩니다..txt 파일을 dictionary (Python v2.7)로 처리하십시오.

모든 n 번째 줄마다 항목을 읽는 CSV로 .txt 파일을 구문 분석했지만 불행히도 패턴이없고 n 번째 숫자가 다릅니다.

예를 들어 "기본 16"이라는 용어 앞에 값을 캡처 한 다음 사전 항목을 만들기 위해 그 다음에 나오는 용어를 캡처하는 방법이 있습니까?

많은 감사

답변

1

음 항목이 줄 바꿈으로 구분된다. 두 번째 줄은 항상 base16입니다. 첫 번째 탭 앞에있는 데이터는 base16 키이고 마지막은 회사 이름입니다.

import urllib 

inputfile = urllib.urlopen("http://standards.ieee.org/develop/regauth/oui/oui.txt") 
data = inputfile.read() 

entries = data.split("\n\n")[1:-1] #ignore first and last entries, they're not real entries 

d = {} 
for entry in entries: 
    parts = entry.split("\n")[1].split("\t") 
    company_id = parts[0].split()[0] 
    company_name = parts[-1] 
    d[company_id] = company_name 

결과의 일부

:

40F52E: Leica Microsystems (Schweiz) AG 
3831AC: WEG 
00B0F0: CALY NETWORKS 
9CC077: PrintCounts, LLC 
000099: MTX, INC. 
000098: CROSSCOMM CORPORATION 
000095: SONY TEKTRONIX CORP. 
000094: ASANTE TECHNOLOGIES 
000097: EMC Corporation 
000096: MARCONI ELECTRONICS LTD. 
000091: ANRITSU CORPORATION 
000090: MICROCOM 
000093: PROTEON INC. 
000092: COGENT DATA TECHNOLOGIES 
002192: Baoding Galaxy Electronic Technology Co.,Ltd 
90004E: Hon Hai Precision Ind. Co.,Ltd. 
002193: Videofon MV 
00A0D4: RADIOLAN, INC. 
E0F379: Vaddio 
002190: Goliath Solutions 
+0

많은 감사 @nightcracker. 이 파일을 다운로드 한 .txt 파일에 연결하는 방법은 무엇입니까? 예를 들어, "oui.txt"와 같이 있습니다. 먼저이 파일에서 항목을 열고 읽는 방법은 무엇입니까? 감사합니다 – thefragileomen

+0

@ thefragileomen : 그 정보로 내 대답을 업데이 트했습니다. 내 대답으로 문제가 해결되면 내 대답의 왼쪽에있는 "대답 수락"버튼을 클릭하십시오. – orlp

1
result = dict() 
for lig in open('oui.txt'): 
    if 'base 16' in lig: 
     num, sep, txt = lig.strip().partition('(base 16)') 
     result.[num.strip()] = txt.strip() 
1
def oui_parse(fn='oui.txt'): 
    with open(fn) as ouif: 
     content = ouif.read() 
    for block in content.split('\n\n'): 
     lines = block.split('\n') 

     if not lines or not '(hex)' in lines[0]: # First block 
      continue 

     assert '(base 16)' in lines[1] 
     d = {} 
      d['oui'] = lines[1].split()[0] 
     d['company'] = lines[1].split('\t')[-1] 
     if len(lines) == 6: 
      d['division'] = lines[2].strip() 
     d['street'] = lines[-3].strip() 
     d['city'] = lines[-2].strip() 
     d['country'] = lines[-1].strip() 
     yield d 

oui_info = list(oui_parse()) 
1
>>> import urllib 
... 
... f = urllib.urlopen('http://standards.ieee.org/develop/regauth/oui/oui.txt') 
... d = dict([(s[:6], s[22:].strip()) for s in f if 'base 16' in s]) 
... print d['000001'] 
XEROX CORPORATION