2017-10-28 8 views
1

Word文書のテーブルを読み込んでそこからデータフレームを作成するいくつかのコードがあります。特定のテキストのWordテーブルからの検索Python docx

import numpy as np 
import pandas as pd 
from docx import Document 

#### Time for some old fashioned user functions #### 
def make_dataframe(f_name, table_loc): 
    document = Document(f_name) 
    tables = document.tables[table_loc] 

    for i, row in enumerate(tables.rows): 
     text = (cell.text for cell in row.cells) 
     if i == 0: 
      keys = tuple(text) 
      continue 

     row_data = dict(zip(keys, text)) 
     data.append(row_data) 
    df = pd.DataFrame.from_dict(data) 
    return df 


SHRD_filename = "SHRD - 12485.docx" 
SHDD_filename = "SHDD - 12485.docx" 

df_SHRD = make_dataframe(SHRD_filename,30) 
df_SHDD = make_dataframe(SHDD_filename,-60) 

ファイル(例えばSHRDは32個のテーブルを持っており、私が探しています1が最後まで秒ですが、SHDDファイルは280個のテーブルを持っている、と私は探しています1は、第60回で異なるため、端から。しかし、それは必ずしもそうではないかもしれない。

私は、ドキュメント内のテーブルを検索し、cell[0,0] = 'Tag Numbers' 1の作業を開始するにはどうすればよい。

答えて

2

あなたは、テーブルを反復処理し、テキストを確認することができます1つ目のセルに複数のテーブルがある場合に備えて、データフレームのリストを返すように出力を変更しました。条件を満たす表がない場合は空のリストを作成します。

def make_dataframe(f_name, first_cell_string='tag number'): 
    document = Document(f_name) 

    # create a list of all of the table object with text of the 
    # first cell equal to `first_cell_string` 
    tables = [t for t in document.tables 
       if t.cell(0,0).text.lower().strip()==first_cell_string] 

    # in the case that more than one table is found 
    out = [] 
    for table in tables: 
     for i, row in enumerate(table.rows): 
      text = (cell.text for cell in row.cells) 
      if i == 0: 
       keys = tuple(text) 
       continue 

      row_data = dict(zip(keys, text)) 
      data.append(row_data) 
     out.append(pd.DataFrame.from_dict(data)) 
    return out 
+0

ありがとうございます。私が追加しなければならなかったのは、 'first_cell_string = first_cell_string.lower()。strip()'だったので、検索文字列がWord文字列と一致した。 –

関連する問題