Searching for a particular label or note in a DWG drawing does not have to mean opening the file in a CAD editor and checking each annotation manually. With Python, you can inspect the drawing’s text entities and identify matching room names, equipment labels, or other annotations.
This article shows how to search text in a DWG file using Python with Aspose.CAD for Python via .NET. You will load a DWG file, search single-line and multiline text, print the matching content and its layer, and optionally limit the search to one layer. The example reads the drawing without changing or exporting it.
Install Aspose.CAD for Python via .NET
To follow the example, you need a Python environment supported by Aspose.CAD, a DWG file that contains text annotations, and the Aspose.CAD package. The Aspose.CAD Python product page lists Python 3.9 or later among its requirements.
Install the package from PyPI:
pip install aspose-cad
You can also consult Aspose.CAD installation guide for package setup details.
For this tutorial, put a file named
drawing.dwgin your working directory. Ideally, use a drawing that contains both single-lineTEXTand multilineMTEXTannotations so you can check both cases.
How to Search Text in a DWG File Using Python
DWG files store drawing content as entities. For text searching, two useful entity types are:
- TEXT (
CadText): Typically represents a single-line annotation. Itsdefault_valueproperty provides the text value. - MTEXT (
CadMText): Represents multiline text. Itsfull_clear_textproperty returns the text without its CAD formatting codes.
You can search these entities without first converting the drawing to an image or PDF. The workflow is straightforward:
- Load the DWG file with
Image.load()and access it as aCadImage. - Iterate through the drawing’s
entitiescollection. - Identify
TEXTandMTEXTentities and read their content. - Compare each value with your search term.
- Display each match and the layer to which the entity belongs.
The following example implements these steps. It searches the drawing’s top-level TEXT and MTEXT entities; text inside nested blocks and attributes is discussed separately below.
Find Text in a DWG Drawing Programmatically
Suppose you need to locate every annotation containing the word valve in an engineering drawing. The following code searches for that word regardless of capitalization and reports the layer of each matching entity.
import aspose.cad as cad
from aspose.pycore import cast
# Path to the source drawing and the text to find.
dwg_path = "drawing.dwg"
keyword = "valve"
if not keyword:
raise ValueError("The search keyword must not be empty.")
# Load the DWG as a CAD image.
image = cad.Image.load(dwg_path)
cad_image = cast(cad.fileformats.cad.CadImage, image)
entity_types = cad.fileformats.cad.cadconsts.CadEntityTypeName
matches = 0
# Search top-level text entities.
for entity in cad_image.entities:
text_value = None
if entity.type_name == entity_types.TEXT:
text_entity = cast(
cad.fileformats.cad.cadobjects.CadText, entity
)
text_value = text_entity.default_value
elif entity.type_name == entity_types.MTEXT:
mtext_entity = cast(
cad.fileformats.cad.cadobjects.CadMText, entity
)
text_value = mtext_entity.full_clear_text
# Match a word or phrase without case sensitivity.
if text_value and keyword.casefold() in text_value.casefold():
matches += 1
print(f"Match: {text_value}")
print(f"Layer: {entity.layer_name}")
print("---")
print(f"Total matches: {matches}")
How the Code Works
The Image.load() method opens the DWG file. The cast() helper then gives you access to CadImage members, including its entities collection.
Each entity has a type_name that identifies what kind of drawing object it represents. When that type is TEXT, the code reads CadText.default_value. When the type is MTEXT, it uses CadMText.full_clear_text to obtain the readable multiline value.
Python’s casefold() method makes the comparison case-insensitive, so valve, Valve, and VALVE are all potential matches. The condition also supports partial matches: searching for valve will match an annotation such as Main Valve.
Finally, entity.layer_name identifies the CAD layer containing each result. This can help you locate a matching note when the drawing contains separate layers for equipment, dimensions, and annotations.
Expected Output
For a sample drawing with two matching annotations, the output could look like this:
Match: Main Valve
Layer: Plumbing
---
Match: VALVE CONTROL ROOM
Layer: Annotations
---
Total matches: 2
This is an illustrative output. Your results depend on the actual text entities in your DWG file. If the search finds no matching top-level TEXT or MTEXT entities, the final line will report Total matches: 0.
Search Text in a Specific DWG Layer
Some drawings organize content into dedicated layers, such as Annotations, Equipment, or Plumbing. If you already know the layer containing the text you need, you can filter entities before checking their values.
In the main example, define the target layer before the loop:
target_layer = "Annotations"
Then insert this condition immediately after for entity in cad_image.entities::
if entity.layer_name.casefold() != target_layer.casefold():
continue
The rest of the search code stays unchanged. Only entities whose layer name matches Annotations will be examined for the keyword. This comparison ignores capitalization in the layer name as well.
The filter works on each entity’s assigned layer; it does not by itself expand nested block content or search external references.
Find Exact Text or Extract Text from DWG
The main example uses a case-insensitive substring search. You can adapt the comparison to fit your task.
Find an exact text value: Replace the matching condition with the following expression to exclude longer annotations that merely contain the keyword:
if text_value and text_value.casefold() == keyword.casefold():
Use a case-sensitive search: Keep the original capitalization on both sides of the comparison:
if text_value and keyword in text_value:
Extract all top-level TEXT and MTEXT values: Remove the keyword comparison and process every nonempty text_value. For example, after the entity-type checks in the main loop, you can append text to a list instead of testing the keyword:
if text_value:
extracted_text.append(text_value)
Initialize extracted_text = [] before the loop if you use this variation. You can then write the collected strings to a text file or use them in a separate search or indexing workflow. This variation still covers only the entity types handled by the loop.
Why Some DWG Text May Not Appear in Search Results
A DWG drawing can contain text in more places than the top-level TEXT and MTEXT collection. If the code returns fewer matches than expected, check the following possibilities:
- Text inside blocks: A block may contain its own entities. You need additional traversal to inspect those entities.
- Block attributes: Some text values are stored in
CadAttriborCadAttDefentities associated with inserted blocks. These are not included in the main example. - External references: Text in an externally referenced drawing may require processing the referenced content separately.
- Raster content: Letters that appear only as pixels in an attached image are not CAD text entities. Finding those words requires OCR rather than this entity-based approach.
- Other annotation types: Dimensions, leaders, and specialized CAD objects may store or generate text differently and need separate handling.
The Aspose.CAD documentation on working with text identifies CadText, CadMText, CadAttrib, and CadAttDef as relevant text-bearing entity types. For a broader search, extend the traversal to include those additional objects and test it against the structure of your drawings.
If Image.load() fails, check the file path first, then confirm that the DWG file is valid and uses a supported format. For unexpected results, start with a small drawing whose annotation values and layers you can verify in a CAD viewer.
Frequently Asked Questions
Can Python search text inside a DWG file without AutoCAD?
Yes. With Aspose.CAD for Python via .NET, you can open a supported DWG file and inspect text entities programmatically. AutoCAD does not need to be installed for this workflow.
How can I find a specific word in a DWG drawing using Python?
Load the file as a CadImage, iterate through its entities, read the TEXT and MTEXT values, and compare each value with your keyword. The example above uses casefold() and Python’s in operator to find case-insensitive partial matches.
Can I extract all text from a DWG file using Python?
You can collect text from supported entity types, including CadText and CadMText. A comprehensive extraction process should also inspect relevant block contents, attributes, and other annotation objects instead of relying only on the top-level entity loop.
Get a Free Temporary License
You can request a free 30-day temporary license to evaluate Aspose.CAD for Python via .NET without evaluation restrictions. The temporary-license request process requires an eligible business email address.
See the Aspose.CAD licensing guide for information about applying a license in your Python application.
Free Learning Resources
Explore these resources for more information about processing DWG drawings and working with CAD entities in Python:
- Aspose.CAD for Python via .NET Documentation – Setup instructions, drawing operations, and development guides.
- Work with Text in CAD Drawings – Information about text-bearing entities in DWG and DXF files.
- Aspose.CAD Python API Reference – Classes, entity types, properties, and methods.
- Aspose.CAD for Python Downloads – Product releases and package resources.
- Aspose.CAD Free Support Forum – Ask questions about CAD file processing and API behavior.
Conclusion
You can search text in a DWG file using Python by loading the drawing, inspecting its TEXT and MTEXT entities, and comparing their values with a keyword. The same workflow can report matching layers, narrow searches to a particular layer, or collect text for further processing. For drawings that contain block attributes or nested annotations, extend the entity traversal before relying on the results as a complete text inventory.
