ezdxf how to extract the tags associated with text in the block layout

2.6k Views Asked by At

How to extract the tag associated with the text value from dxf block layout.

Here is a screenshot:

drawing file with a format layout

For example, TITLE is the header that comes as part of drawing format layout, DESC is the text tag associated with the TITLE Content "BASE". How can I extract the DESC (&TITLE) with TITLE Content.

I tried viewing the dxf file in notepad but doesn't have these tag entries. Is there a way to extract not only the text but also the associated tag?

2

There are 2 best solutions below

0
On

For those that are new to ezdxf (like me), it took me a while to realise that on scenario 2 above, the .get_text() method in MTEXT has been replaced with .text since ezdxfVersion 0.10 released on 2019-09-01.

Therefore, I had to replace the following code in scenario 2 above:

# search for MTEXT entities
for mtext in msp.query('MTEXT')
print("MTEXT content: {}".format(mtext.get_text())

with the following:

# search for MTEXT entities
for mtext in msp.query('MTEXT')
print("MTEXT content: {}".format(mtext.text)

Other than that, the code from mozman worked great to extract the tags associated with text in layouts (msp or psp).

4
On

As the name ezdxf already says, ezdxf works with DXF files not with DWG or DRW files, unlike DXF, is DWG an undocumented binary encoded AutoCAD file format.

Maybe you can export your files as DXF files to process them with ezdxf:

Scenario 1, ATTRIB attached to block reference INSERT:

doc = ezdxf.readfile('YourFile.dxf')
msp = doc.modelspace()
# block reference attributes (tags) are stored in the INSERT entity
for insert in msp.query('INSERT')
    print(str(insert))
    for attrib in insert.attribs():
        print("Tag: {}, Value: {}".format(attrib.dxf.tag, attrib.dxf.text))

Scenario 2, ATTRIB, MTEXT or TEXT as standalone entity in modelspace or paperspace:

msp = doc.modelspace()
# or getting paperspace:
# psp = doc.layout('TabName')
# search for ATTRIB entities
for attrib in msp.query('ATTRIB')
    print("Tag: {}, Value: {}".format(attrib.dxf.tag, attrib.dxf.text))
# search for MTEXT entities
for mtext in msp.query('MTEXT')
    print("MTEXT content: {}".format(mtext.text)
for text in msp.query('TEXT')
    print("TEXT content: {}".format(text.dxf.text)

Scenario 3, entities located in BLOCK definitions:

for block in doc.blocks:
    print('searching in BLOCK definition {}'.format(block.name))
    # search for ATTRIB entities (or MTEXT and TEXT see above)
    for attrib in block.query('ATTRIB')
        print("Tag: {}, Value: {}".format(attrib.dxf.tag, attrib.dxf.text))
    # or like scenarion 1, search for INSERT with attached ATTRIB
    for insert in block.query('INSERT'):
        for attrib in insert.attribs()
            print("Tag: {}, Value: {}".format(attrib.dxf.tag, attrib.dxf.text))