2012-02-16 4 views
0

この問題があります。元のソースファイルはmhtml形式のlxmlを使用して処理しています。これらはExcelファイルです。私はヘッダー要素 'th'要素を含む行を見つける必要があります。私はヘッダ要素を使いたいが、順番どおりにすべてを処理するためには、ヘッダ要素を必要とする。lxmlで要素をテストするときの円形性の回避

私がしてきたことは、th要素のすべてを見つけ出し、e.getparent()関数を使って行を取得することです(行の子であるため)。しかし、私はth要素を2回引っ張って、それらを見つけて行を取得し、再度それらを行から取り出して、私が探しているデータを解析する必要があります。 これはこれを実行する最善の方法ではありませんので、私が紛失しているものがあるかどうか疑問に思っています。

は、ここに私のコードのすべてのtrタグ超える

from lxml import html 
theString=unicode(open('c:\\secexcel\\1314054-R20110331-C201-F60-SEQ132.xls').read(),'UTF-8','replace') 
theTree=html.fromstring(theString) 
tables=[e for e in theTree.iter() if e.tag=='table'] 
for table in tables : 
    headerCells=[e for e in table.iter() if e.tag=='th'] 
    headerRows=[] 
    for headerCell in headerCells: 
     if headerCell.getparent().tag=='tr': 
      if headerCell.getparent() not in headerRows: 
       headerRows.append(headerCell.getparent()) 
    for headerRow in headerRows: 
     newHeaderCells=[e for e in headerRow.iter() if e.tag=='th'] 
     #Now I will extract some data and attributes from the th elements 

答えて

1

反復され、そしてあなたが内部にはthを見つけていないときだけ、次のいずれかに移動します。

EDIT。これはどのようにある:

from lxml import html 
theString=unicode(open('c:\\secexcel\\1314054-R20110331-C201-F60-SEQ132.xls').read(),'UTF-8','replace') 
theTree=html.fromstring(theString) 
for table in theTree.iter('table'): 
    for row in table.findall('tr'): 
     headerCells = list(row.findall('th')) 
     if headerCells: 
      #extract data from row and headerCells 
+0

これは私がやっていたよりもはるかにpythonicを探していたものです – PyNEwbie

1

は二回それをやって回避するには、行の要素をキーとする辞書を使用することができますし、1回通過で行うことができ、assocatedリストに指定した行からすべてのヘッダーセルを蓄積しますテーブルの要素見たときに行を整列させるためには、を組み込みのcollectionsモジュールから使用することができます。これは、これらの行に沿った何かが書かれることを可能にするでしょう:

from lxml import html 
from collections import OrderedDict 
f='c:\\secexcel\\1314054-R20110331-C201-F60-SEQ132.xls' 
theString=unicode(open(f).read(),'UTF-8','replace') 
theTree=html.fromstring(theString) 
tables=[e for e in theTree.iter() if e.tag=='table'] 
for table in tables: 
    headerRowDict=OrderedDict() 
    for e in table.iter(): 
     if e.tag=='th': 
      headerRowDict.setdefault(e.getparent(), []).append(e) 
    for headerRow in headerRowDict: 
     for headerRowCell in headerRow: 
      # extract data and attributes from the <th> element from the row... 
関連する問題