2011-11-09 8 views
1

私は現在、this .txt fileの情報を処理して解析したいと考えています。ファイルはタブで区切られているように見えます。私は、辞書の値として基数16の値(すなわち、000000)を、そして辞書の値として会社の名前(すなわちXerox Corporation)を解析しようとしています。したがって、たとえば、私の辞書でキー000001を検索すると、Xerox Corporationがそれぞれの値として返されます。辞書にある.txtファイルを処理する(Python v2.7)

n行ごとにエントリを読み取るcsvとして.txtファイルを解析しようとしましたが、残念ながらパターンがなく、n番目の番号が異なります。

たとえば、 "base 16"という用語の前にある値をキャプチャし、それに続く辞書エントリを作成するための用語はありますか?

感謝

答えて

1

まあエントリは2つの改行で区切られています。 2行目は常に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 
関連する問題