Welcome. I'm glad you're here. This page explains how the mentorship works. That's all you need to read today.
The Core Course is ten (10) short lessons, each teaching a single skill. Lessons 5 through 10 end with a portfolio item.
For each portfolio item:
Go at whatever pace fits your life. An expedient pace would be about one lesson a week, but if something comes up and you need a break, just tell me.
By the end, the portfolio items add up to a small portfolio of real technical writing samples you can show employers.
The mentorship should serve you and your goals. Therefore you may choose between a structured or unstructured mentorship.
The Core Course is the structured option, and it's optional. The goal of the Core Course is for you to finish with seven (7) portfolio items and a working knowledge of:
If you'd prefer an unstructured mentorship, or you already have a definite idea of what you want to learn from me, that is also acceptable. Tell me, and we'll focus on that instead.
You do not need to know how to code.
No programming, no paid software, and no prior technical writing experience are required for the Core Course.
Below the Core Course in the menu, you'll see two optional sections:
My name is Jonathan. I've worked as a technical writer in the defense industry for 9+ years, writing manuals, procedures, and training materials.
I can teach you the technical writing style, help you build portfolio pieces, and answer questions about the profession. If you're curious about the software and markup languages I use, they're listed in the Toolbox under "Software and Languages".
The single most useful skill in technical writing: writing steps a reader can follow without getting lost.
Technical writing uses two (2) main styles:
This course focuses mostly on the procedural style: writing the chronological steps of a task.
When writing a procedure, the most important thing is to maintain context. The reader should always know where they are and whether things are going right.
To do that, think of each step in three (3) parts: prepositional phrase , command , and result .
Here is an example:
From Category drop-down, select an appropriate category. The item record updates to show the new category.
| Part | Text from the example |
|---|---|
| Prepositional phrase | From Category drop-down, |
| Command | select an appropriate category. |
| Result | The item record updates to show the new category. |
In the Category list, select a category. The item record shows the new category.
| Part | Text from the example |
|---|---|
| Prepositional phrase | In the Category list, |
| Command | select a category. |
| Result | The item record shows the new category. |
The prepositional phrase tells the reader where they need to be before executing the command. In other words, this is the context.
It can be a space on the screen, like a desktop, window, pane, or dialog:
It can link more than one location to guide the reader:
It can be a field, box, or drop-down:
When the context changes from one step to the next, start the step with a prepositional phrase.
When the context doesn't change, you can leave it out or move it after the command so the sentence flows more naturally.
In practice, watch for windows closing. Whenever the current context disappears, add a prepositional phrase to the next step.
The command tells the reader what to do, using a present tense verb (e.g., click, right-click, select, enter, verify).
If a numbered step has no command, it isn't a real step.
With this in mind, when you see a step that isn't a real step, merge it into the previous step or turn it into a note. If you're unsure, try adding a command such as "observe", "ensure", or "verify".
The result tells the reader what should happen after the command. It's how they know the step worked.
Try to always include a result. Exceptions exist, such as several short, repetitive steps where nothing visible happens until later.
Try to use a present tense verb in the result ("displays", not "will display"; "changes", not "will change"), unless the result is significantly delayed.
When the result leads into the next step's prepositional phrase, it maintains the most context:
[...] Run Report dialog displays.
From Run Report dialog, [...]
[...] The Run Report dialog box opens.
In the Run Report dialog box, [...]
This can feel wordy, but it helps a lot with confusing tasks. Use your best judgment: where are the "pain points"?
Style varies by employer
You may notice my examples drop small words like "the" ("From Category drop-down, select..."). That's common in defense and military manuals.
Commercial style guides, such as the Microsoft Writing Style Guide, usually keep those words and may phrase things differently ("In the Category list, select...").
Every employer has its own style guide. For parity with existing documentaion, you use the house style. The general three-part structure I've described (where, what, result) works in every style.
To compare, many examples in Lessons 1 through 5 have two tabs. Military shows the style I use at work. Retail shows a commercial software style based on the Microsoft Writing Style Guide.
Sometimes you'll find content that blurs the line between informational and procedural. If you can't make it 100% procedural, that's okay. You might even leave unclear content alone and focus your effort elsewhere.
As long as you keep the style in mind, your edits will make the content better than it was before.
How a single unit of documentation is put together, and how to title it.
A "topic" is a self-contained unit of information about a single subject or task. Think of it as one section of a manual or one page of online help.
There are three (3) basic layouts for a topic:
General information uses the informational style. Procedural steps use the procedural style.
There are two (2) types of topic titles:
When writing a topic title, capitalize the first word and every other word except short articles, coordinating conjunctions, certain pronouns, and short prepositions:
| Articles | a, an, the |
| Coordinating Conjunctions | and, but, or, nor, for, yet, so |
| Pronouns | their, his, her, its, who, whom, whose |
| Short Prepositions (usually 3 letters or fewer) | at, by, for, in, of, on, to |
Do capitalize these words: with, from, over, under, into, about, before, during, after, through, between, as, than, until, onto, upon, because, while.
(This is my house rule. Some style guides uncommonly lowercase longer prepositions and conjunctions. As always, follow the house rule appropriate to the project.)
General information has the fewest rules, but the intent is always to inform, not to persuade or entertain.
General information can include:
General information cannot include instructions. That's what procedural steps are for.
Procedural steps go in an ordered (numbered) list.
Procedural steps can include:
In Microsoft Word, when your cursor is in a numbered step and you press [Tab], the step indents and moves to the next level of numbering. The order is: 1, a, i, (1), (a), (i).
Here is what nested steps look like:
Deeper nesting means deeper context within the task. That can be conceptual (breaking a task into smaller tasks) or on screen (when a dialog opens, context moves "forward"; when it closes, context moves "back").
A "parent" step with sub-steps under it must still be a complete idea, so don't just write "Do the following:". Instead, summarize the task with a present tense verb, such as "Add a supplier to the item:".
The building blocks inside a topic: tenses, lists, images, alerts, tables, and figures.
In general information, use whatever verb tenses are accurate. A paragraph might be about the past, the future, or something that only happens under certain conditions.
In procedural steps, favor the present tense (imperative mood). Here's what I mean:
From Category drop-down, select an appropriate category. The item record updates to show the new category.
From Category drop-down, the user selects their desired category. The item record will update to show the new category.
In the Category list, select a category. The item record shows the new category.
In the Category list, the user selects a category. The item record will show the new category.
The second version has two (2) problems:
The reader is doing the task right now, so the result should be in the present tense too, unless it's significantly delayed. If it is, say when: "The item record will update after the nightly sync."
Use bulleted (unordered) lists for anything that isn't a sequence of steps.
Start every item the same way: all verbs in the same tense, or all nouns. This is called parallel structure (or parallelism).
In my house style, the final item ends with a period.
Bulleted lists are also a good fix for long sentences with four (4) or more commas:
The Stockroom menu bar enables the user to:
The same sentence with serial semicolons:
The Stockroom menu bar enables the user to create new inventory lists; save, load, and duplicate item records; access 17 editing windows, including those for pricing and suppliers; and run the End-of-Day Reconciliation (EDR) report.
Both of these approaches are useful when you're editing someone else's run-on sentence and don't want to accidentally change its meaning.
As for when to use these two approaches, I prefer bulleted lists at the top of topics and in summaries (because they are easy to scan), and I prefer serial semicolons in the middle of longer explanatory paragraphs (i.e., about history or theory).
Inline images are small pictures inside a sentence, usually software buttons or icons. I recommend putting them in parentheses after the bolded name.
In bulleted lists, don't use the icon as the bullet. (In these examples, "[icon]" stands in for the picture.)
put the image in parentheses after the bolded name
use the image as the bullet
[icon] Copy: Copies the item record.
[icon] Paste: Pastes the item record.
[icon] Label: Opens Print Label dialog.
Never put inline images in titles or captions. They can break your table of contents.
Notes, cautions, and warnings go above the paragraph or step they apply to, so the reader sees them before acting.
If you must stack them, the order is warnings, then cautions, then notes. Keep them on the same page as the content they apply to, or the reader might miss them.
Don't put instructions in notes, cautions, or warnings. Put information only. If you need an instruction, write a step.
For example, this standard warning goes before any step that involves moving a heavy item:
WARNING
The [item] requires a two-person lift. Items weighing over 20.5 kilograms (45 pounds) shall be placed for two-person handling.
Warnings and cautions often include an icon that shows the type of hazard. You can use the icons in my warning icons folder (Google Drive) in your own work. To save one, open it and select the Download button at the top of the preview.
The table caption goes above the table. Keep the caption on the same page as the start of the table; Microsoft Word paragraph styles can force this via the "Keep with next" property.
Add figures (images) of entire windows, entire dialogs, or areas that are easy to recognize without extra context. Don't add a figure of just a tiny button.
The figure caption goes below the figure. Keep it on the same page as the figure.
If an image is mostly white around the edges, add a thin black outline.
Draw red or yellow boxes around the parts the reader interacts with. Red boxes stand out over a light background; yellow boxes stand out over a dark background. In my house style, a blue box indicates zooming in.
When referencing nearby figures, avoid phrases like "as shown in Figure 3 below." They add numbers that can break when content is edited or reused, and they confuse readers if the image doesn't load. A topic should be detailed enough to follow without its figures, which are supplementary.
For the same reason, never write "make it look like the figure." If the image is missing or blurry, the reader gets stuck.
Keep images within the page margins.
If an image contains text, resizing it resizes the text, so try to keep text sizes consistent across images of the same kind (parallel structure again).
And always check that photos of hardware or facilities don't show anything sensitive in the background.
In Word, try to keep your whole document at six (6) levels of headings or fewer (the Heading 1 through Heading 6 paragraph styles).
In XML-based authoring, the rules of the markup decide where titles are allowed. That's covered in Lesson 10.
Consistent words for common things on screen. Readers trust documentation that names things the same way every time.
These are the terms I use. Your employer's style guide may differ; what matters most is picking one term and using it consistently.
| Favored | Not Favored |
| drop-down | dropdown, drop down |
| pop-up menu | popup menu, popup |
| checkbox | check box |
| radio button | radial button |
| dialog | dialogue, dialog box, dialogue box |
| field (when named), text box (when not named) | text field, text area |
| scrollbar | scroll bar, scroll-bar |
| sidebar | side bar, side-bar |
| toolbar (when horizontal) | tool bar, tool-bar |
| tool palette (when vertical) | - |
| taskbar | task bar, task-bar |
| menu bar | menubar, menu-bar |
| title bar | titlebar, title-bar |
| Favored | Not Favored |
| select (for buttons, drop-downs, and similar) | left-click, press the left mouse button, perform a single click |
| click (for tiny targets like expand/collapse nodes, the X in a corner, or empty space) | left-click, left click |
| double-click | double click, click twice in quick succession |
| right-click on | right click on, press the right mouse button |
| enable (for the means to do something, not for permission) | allow |
| enter | type, type in |
| log in, log in to | login, login to |
| plug into | plug in to |
"Enter" also implies pressing [Enter] when applicable, so you don't need to write it. Use "enter" even when the user doesn't press [Enter].
| Favored | Not Favored |
| required, as required, as needed | desired, as desired |
| left, right | left-hand, right-hand |
A window is a rectangular container, managed by the operating system, that displays an application's graphical user interface (GUI). An application may have any number of windows.
A title bar runs along the top of a window. In the Windows OS, a window has three (3) buttons at the top right: minimize, restore down/maximize, and close. (Closing a window sends a close request to the application, which may exit or keep running in the background.) On a Mac, the three buttons (close, minimize, and full screen) are at the top left, and the menu bar runs along the top of the screen instead of inside the window.
A menu bar, usually located just under the title bar, is a horizontal bar of drop-down menus such as File, Edit, View, and Help. Sometimes the title bar and menu bar are the same bar.
"Panes" and "panels" divide windows. These terms are not strictly standardized.
A dialog is a small window that exists to complete one task, then close. A standard dialog blocks its parent window until dismissed and usually has three (3) or fewer buttons, like OK and Cancel.
A dialog can be used for:
If a dialog's name reads like a sentence or has punctuation, put it in quotation marks: From "Delete Item?" dialog, select Yes. Or simply say "dialog", since only one can have focus at a time. The longer or more abstract the name, the more weight you should put on just calling it a "dialog".
These are live examples. Click them to see how each one behaves.
These are checkboxes. You can check or uncheck any combination.
These are radio buttons. You can select only one per group.
A field. You can enter free-form text.
A spinner. Use the arrows to change the value within limits (here, 1 to 10).
A drop-down. You select one option from a set.
In a menu bar, its options form a "drop-down menu" that runs commands or opens windows. You don't need to name it: "From Stockroom menu bar, select Edit > Item Properties > Pricing. Pricing window displays."
Elsewhere, its options form a "drop-down list" that is usually just for making a selection.
A menu that appears when you right-click is a pop-up menu. Right-click anywhere on this page to see one.
A date picker:
A time picker:
A color picker:
A file picker. In practice, I'd call this the Choose File button. It opens a File Explorer window (a Finder window on a Mac).
When to bold, capitalize, and quote, so readers can spot what to act on.
In procedural steps, bold the name of the thing the reader interacts with, plus selections and text to enter.
Don't bold the type of thing it is (button, drop-down, key). Don't bold anything in the prepositional phrase.
That last rule is military style. Commercial guides, like the one behind the Retail tab, bold the label in the prepositional phrase too ("In the Category list"). Follow your employer's guide.
Underlines below only show what's bolded. Don't underline in real documentation.
From Category drop-down, select an appropriate category, then select OK.
From Category drop-down, [...]
From Category drop-down, [...]
From Category drop-down, [...]
From Search field, enter the item's SKU number. The inventory list scrolls to the matching item.
Right-click on the selected item and select Move > Transfer to Location. Then click a destination shelf on the warehouse map. The item record updates to show the new location.
Underlines below only show what's bolded. Don't underline in real documentation.
In the Category list, select a category, and then select OK.
In the Category list, [...]
In the Category list, [...]
In the Category list, [...]
In the Search box, enter the item's SKU number. The inventory list scrolls to the matching item.
Right-click the item, select Move > Transfer to Location, and then select a destination shelf on the warehouse map. The item record shows the new location.
A real-world example, creating a table of contents in Word:
On a Mac, press [Command] + [F9] instead of [CTRL] + [F9], and [Option] + [F9] instead of [ALT] + [F9]. If the F keys change the volume or brightness, also hold [Fn]. To right-click, hold [Control] and click.
For keyboard keys, bold the key name in brackets: press [Q], press [Enter], press [CTRL] + [ALT] + [DEL].
Italic: not used. If you choose to use it, do so sparingly and for one consistent purpose.
Underline: only for hyperlinks. The same advice applies if you use it otherwise.
Capitalize the name of the item, not what it is: Confirm button, Category drop-down, [Enter] key. It's the same rule as bolding.
Don't capitalize ordinary words just because they appear in software. Capitalization is for names.
You can capitalize names of roles in a system ("Admin", "Maintainer") and formal stages of a process ("Requirements Analysis phase").
When an item's official name is in all caps, decide whether to match it exactly. I prefer to match it.
Use quotation marks around unfamiliar terms that would otherwise interrupt the sentence, and around names that contain punctuation or read like a sentence:
From "Are you sure you want to delete all items in this location?" dialog, select "Yes, delete all".
In the Are you sure you want to delete all items in this location? dialog box, select Yes, delete all.
You may be surprised what real software names things. When the quoted text is bolded, bold the quotation marks too.
Each mark has its own job:
| Mark | Use it for | Example |
|---|---|---|
| Hyphen (-) | joining words into one term, and part numbers | two-person lift, KP-900 |
| En dash (–) | ranges, meaning "to" or "through" | Repeat steps 3–5. Torque to 30–35 in-lb. |
| Em dash (—) | a break or aside in a sentence, in place of commas, parentheses, or a colon | Remove the cover—all four screws—before you begin. |
Don't mix an en dash with words: write "from 3 to 5," not "from 3–5." Style guides differ on spacing around em dashes, so follow your employer's guide. In procedures, an aside usually works better as its own sentence, so you'll rarely need an em dash at all.
Template: MentorshipAsset1_TemplateProcedure.docx (Google Drive). To save your own copy, select File > Download > Microsoft Word (.docx).
Using the template, write a software procedure of about 8 to 15 steps in the technical writing style, or rewrite an existing public procedure to make it better. Choose any subject that interests you and would suit a portfolio.
Not sure what to pick? Try one of these:
If you rewrite an existing procedure, use publicly available documentation, not anything from your employer that isn't public.
When you're ready, share the file with me through Google Drive (with comment access) or send it by email, and I'll add my feedback as comments.
This is a labeled diagram with a table that explains what each part does.
A Controls and Indicators topic shows the locations of the interactive parts of hardware or software.
Which parts to include depends on the audience. For a consumer product, you might include ports, screw holes, and mounts. For equipment your company installs as part of a larger system, leave those out, because the user is not intended to interact with them. Ask yourself what the user actually needs to know.
A Controls and Indicators topic has, at minimum, one (1) diagram and one (1) table.
For square images (including collages), labels start at 11 o'clock and proceed clockwise.
The dotted line is a margin. Callout lines start at the margin, and the numbers sit between the margin and the outer edge of the canvas.
For wide images (especially toolbars), number left to right. Consider making the canvas as wide as the space between the page margins:
Labels can also go below, angled or straight:
For tall images (tool palettes, remote controls), number top to bottom:
You can also draw a red box around part of the image and label it with one number, then explain it in the table. This keeps the diagram clean when you'd otherwise have arrows pointing into the middle. The table can then use bulleted lists within individual rows to describe multiple items in the red box.
I use Adobe Illustrator, but you don't need it specifically. PowerPoint, Google Slides, or any free image editor can draw boxes, lines, and numbers.
The table has three (3) columns: label number, name, and description.
As with procedures, describe what each part does with a present tense verb. If something is conditional or delayed, say when it happens. This part of a manual describes; it doesn't instruct.
Table 1. Stockroom Main Window Controls and Indicators.
| # | Name | Description |
|---|---|---|
| 1 | New Item button | Creates a blank item record in the current location. The default category is Uncategorized. |
| 2 | Low-Stock Alert checkbox | When checked, the system highlights items whose quantity is below their reorder threshold. |
| 3 | Item Details button | Opens Item Details window for editing the price, supplier, and reorder threshold of the selected item. |
| 4 | Warehouse Map Panel | Displays shelf locations and the items stored on each shelf. |
Notice "Warehouse Map Panel" is capitalized even though it's made of ordinary words. Sometimes a part simply has no official name. When that happens, I capitalize it in tables and lists (for parallelism) but not in paragraphs ("the warehouse map panel").
The margins are as follows:
Every Controls and Indicators diagram uses the same template margins, so callouts sit in the same allocated area on every Controls and Indicators diagram and never cover the artwork.
The margins are invisible in the exported image.
Figure 1. Item Details Window Toolbar Controls and Indicators.
Table 2. Item Details Window Toolbar Controls and Indicators.
| # | Name | Description |
|---|---|---|
| 1 | New Record button | Creates a blank item record. If the window contains unsaved changes, a "Save changes?" dialog displays. |
| 2 | Open Record button | Opens a file explorer window for loading a saved item record. If the window contains unsaved changes, a "Save changes?" dialog displays. |
| 3 | Save Record button | Saves the current item record. If the record has never been saved, a file explorer window displays for naming the file. |
| 4 | Price History button | Opens Price History dialog showing past prices for the item. |
| 5 | Quantity spinner | Sets the quantity on hand. |
| 6 | Critical checkbox | When checked, marks the item as critical stock. When a critical item's quantity falls below its reorder threshold, a flashing alert appears in the status bar. |
Templates:
As you choose which parts to label, consider whether to include everything, as you would for a commercial product, or only some parts, as you would for equipment that is part of a larger system.
When you're ready, share the file with me through Google Drive (with comment access) or send it by email, and I'll add my feedback as comments.
Templates: the same two templates as Portfolio Item 3, MentorshipAsset3_TemplateControlsAndIndicators.docx and MentorshipAsset4_TemplateAdobeIllustrator.ai (Google Drive). If you do not have access to Adobe Illustrator or its free trial, skip this .ai file.
When you're ready, share the file with me through Google Drive (with comment access) or send it by email, and I'll add my feedback as comments.
Procedures that prove a product works.
Test procedures check whether new hardware, software, or systems meet their requirements. Sometimes the customer runs them; sometimes your team's test lead runs them while the customer watches.
Written well, the text of a test procedure is almost identical to procedural steps, just arranged in a table with at least four (4) columns:
If you include images, consider landscape pages and consistent image widths. Test procedures are often used once and then archived, so how much time you spend on images is a judgment call.
Some test procedures also have a column linking each step to the requirements it proves, and a column for comments. You'll learn those on the job if you need them.
| # | Step | Expected Result | Pass/Fail |
|---|---|---|---|
| 1 | From desktop, double-click Stockroom icon. | Login screen displays. |
|
| 2 | Enter username and password, then select Log In. | Stockroom main window displays. |
|
| 3 | From Stockroom main window toolbar, select New Item. | A blank item record displays with category set to Uncategorized. |
|
Template: MentorshipAsset2_TemplateTestProcedure.docx (Google Drive). To save your own copy, select File > Download > Microsoft Word (.docx).
Using the template, restructure the software procedure you wrote for Portfolio Item 1 into a test procedure. If you prefer, you can write a new test procedure instead.
When you're ready, share the file with me through Google Drive (with comment access) or send it by email, and I'll add my feedback as comments.
A common hardware maintenance procedure.
Remove and Replace (or Remove and Install) topics explain how to safely take out a piece of hardware and put in a new one. They're usually grouped in a manual's maintenance chapter.
Because they can involve heavy objects, ladders, ceiling or rack mounts, and high voltage, these topics tend to have the most warnings.
The top of the topic lists the initial setup: prerequisite conditions (like power off), personnel required (like "Maintainer (2)"), and tools required.
The body has two (2) procedures: remove, then replace. The steps are often close to a mirror image of each other.
Notice the first remove step matches the last replace step, the second matches the second to last, and so on. Underlines show the opposite terms.
INITIAL SETUP
Personnel Required: Maintainer (2)
Tools Required: None
Prerequisites: All print jobs are complete or canceled.
Remove Kestrel KP-900 Label Printer
WARNING
The Kestrel KP-900 label printer requires a two-person lift. Items weighing over 20.5 kilograms (45 pounds) shall be placed for two-person handling.
Replace Kestrel KP-900 Label Printer
WARNING
The Kestrel KP-900 label printer requires a two-person lift. Items weighing over 20.5 kilograms (45 pounds) shall be placed for two-person handling.
So: write one procedure completely, then trace it in reverse, writing the opposite command for each step. Check for breaks in the logic. It will be close to what you need.
Two more things to consider:
Add figures when time permits. Photos and cabling diagrams are especially helpful here.
Template: MentorshipAsset5_TemplateRemoveAndReplace.docx (Google Drive). To save your own copy, select File > Download > Microsoft Word (.docx).
Warning icons: warning icons folder (Google Drive). To save one, open it and select the Download button at the top of the preview.
Cable photos (optional): cable pictures folder (Google Drive). If you want to illustrate cables aligning with the hardware's ports for the replace/install part, you may use these cable pictures.
When you're ready, share the file with me through Google Drive (with comment access) or send it by email, and I'll add my feedback as comments.
A structured approach to problem solving.
Troubleshooting topics help isolate faults in hardware or software. They're organized into three parts:
If another malfunction exists for the same symptom, end with "If problem is not resolved, continue to next malfunction." If it's the last one, end with something like "Remove and replace [item]." Either way, the reader never hits a dead end.
One practical tip: when a troubleshooting topic lists phone numbers or email addresses, check whether they're still valid because they can become outdated.
A topic can have several related symptoms, but this example has one. Defense manuals list everything vertically; commercial documentation often uses a table. Either way, be consistent and use this full hierarchy: symptom, malfunction, corrective actions.
Troubleshoot the Kestrel KP-900 Label Printer
INITIAL SETUP
Personnel Required: Maintainer (1)
SYMPTOM
Printer does not print labels.
MALFUNCTION
Label roll is empty or damaged.
CORRECTIVE ACTIONS
MALFUNCTION
Printer is not in Online mode.
CORRECTIVE ACTIONS
MALFUNCTION
Media sensor, external power, or internal fault.
CORRECTIVE ACTIONS
Troubleshoot the Kestrel KP-900 Label Printer
INITIAL SETUP
Personnel Required: Maintainer (1)
| Symptom | Malfunction | Corrective Actions |
|---|---|---|
| Printer does not print labels. | Label roll is empty or damaged. |
|
| Printer is not in Online mode. |
|
|
| Media sensor, external power, or internal fault. |
|
Template: MentorshipAsset6_TemplateTroubleshootingProcedure.docx (Google Drive). To save your own copy, select File > Download > Microsoft Word (.docx).
When you're ready, share the file with me through Google Drive (with comment access) or send it by email, and I'll add my feedback as comments.
This is background on the tools I use day to day. It's here for the curious, not as a checklist. Nobody expects you to know these.
Here is the software I use. You don't need any of it for the Core Course.
| OxygenXML | For writing XML-based documents. |
| Microsoft Word | For writing OOXML-based documents and generating PDF files (via Adobe Acrobat integration). |
| DITA Open Toolkit | For interpreting DITA code and generating output such as Word files. Free and highly customizable. |
| MadCap Flare | For writing HTML-based documents with advanced versioning features. |
| PTC Arbortext | For interpreting XML code and generating PDF files. |
| Adobe Acrobat | For viewing PDFs. Also for signing and appending signature pages. |
| Snagit | For screenshotting portions of the screen and editing them. |
| Adobe Illustrator | For creating "Controls and Indicators" (or "ctrlind") images. Also for image processing. |
| Jira | For issue tracking and project management in the Internet browser. |
| SmartBear Collaborator | For collaborating with others to comment on a variety of file types and track fixes in the Internet browser. |
| Visual Studio Code | For writing and executing scripts of all kinds. Free and highly customizable. |
Here are the markup and scripting languages I use. Most technical writers know only a few of these, and many know none.
| XML | Extensible Markup Language (XML) code structures data inside "tags":<para>This is a paragraph.</para>XML is a catch-all term; since the language is extensible, various standards exist. |
| XSLT | Extensible Stylesheet Language Transformations (XSLT) code defines how XML code is transformed into other coding languages. |
| XSL-FO | Extensible Stylesheet Language Formatting Objects (XSL-FO) code defines how XML code is transformed into paginated content such as PDFs. |
| DITA | Darwin Information Typing Architecture (DITA) is an open XML standard for topic-based authoring. This interfaces with the DITA Open Toolkit to generate custom output of all kinds. |
| OOXML | Office Open XML (OOXML) is the XML standard used by Microsoft Word, Excel, and PowerPoint. If you change the file extension to .zip, the OOXML is immediately accessible. |
| MIL-STD-40051-2D | MIL-STD-40051-2D is the U.S. Department of Defense standard for preparing page-based technical manuals in XML. A contract's Technical Manual Contract Requirements (TMCR) document says which standard and options a manual must follow. |
| HTML | HyperText Markup Language (HTML) code defines the content and structure of web pages. |
| CSS | Cascading Style Sheets (CSS) code defines the style of web pages. |
| DTD | Document Type Definition (DTD) code defines two (2) distinct things:
|
| Batch scripting language | Windows Batch (.bat/.cmd) code directs the Windows Operating System to perform actions via the console. This is a potential part of the publishing process for DITA Open Toolkit if paid software such as OxygenXML is not used. Python is another option. |
| ANT | Apache Ant build files are XML, usually named build.xml, and exclusively perform "build" scripts. In other words, it performs compiling / packaging / deploying tasks. This is a potential part of the publishing process for DITA Open Toolkit if paid software such as OxygenXML is not used. Python is another option. DITA-OT plugins add their own Ant build files and register them in a plugin.xml file. |
| Python | Python (.py) code is a general-purpose scripting language. Writers can use it to automate repetitive tasks, such as checking acronyms, converting files, or batch editing documents. Like Batch and ANT, it can also run the publishing process for DITA Open Toolkit. See Running a Python Script in the Toolbox. |
DITA is markup, not programming
You do not need to know how to code before you can learn DITA.
DITA is a standardized way of labeling the content of a document to make it modular, reusable, and to give it format, style, and structure. Many documentation teams, especially at larger companies, write this way. This approach is called "structured authoring".
Darwin Information Typing Architecture (DITA) is an open XML standard for topic-based authoring. This code interfaces with the DITA Open Toolkit to generate custom output of all kinds, including MS Word files.
DITA code structures data inside
"tags". For example, <p>This is a paragraph.</p>.
<p> is the opening tag.</p> is the closing tag.There are numerous different tags. The tags designate the character data's role in the document and its position in the hierarchy as standardized by the DTD's rules.
DITA code is just structured data waiting to be transformed.
A ".ditamap" file lists a series of <topicref> (topic reference) tags with hyperlinks to the .dita files that comprise a whole document. The order from top to bottom will match the output. And so will the nesting (i.e., when a topic has a topic nested inside it, the output will have Section 1 followed by Section 1.1).
A ".dita" file contains the title and body of a topic.
The Document Type Definition (DTD) declared at the top of every .ditamap and .dita file defines the rules that XML must follow in order to "validate" against the DITA standard. Validate your code before you publish. There are two kinds of problems:
There are two (2) document types I use: map and topic. Each requires its own DTD declaration at the top.
DITAMAP DTD DECLARATION
<!DOCTYPE map PUBLIC "-//OASIS//DTD DITA Map//EN" "map.dtd">
TOPIC DTD DECLARATION
<!DOCTYPE topic PUBLIC "-//OASIS//DTD DITA Topic//EN" "topic.dtd">
These .dtd files (map.dtd and topic.dtd) come with your code editor and with DITA Open Toolkit. You don't need to read the .dtd files. To use them, all you need to do is start your .ditamap or .dita file with the corresponding DTD declaration, as shown above. This is what gives your code editor a standard for the XML to "validate against". In other words, it associates the file with the rules it should be following.
A code editor like OxygenXML can tell you when something in your code does not validate, either with red squigglies or with error messages in the console when you try to validate.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE map PUBLIC "-//OASIS//DTD DITA Map//EN" "map.dtd">
<map>
<title>Sample DITA Map</title>
<topicref href="1/1000-Introduction.dita"/>
<topicref href="2/2000-Installation.dita">
<topicref href="2/2005-Requirements.dita"/>
<topicref href="2/2010-Setup.dita"/>
</topicref>
<topicref href="3/3000-Usage.dita"/>
</map>
The first line is the XML declaration. It declares the file as XML and is always the same even for non-DITA XML files.
The second line declares the DTD for ditamap, which is map.dtd.
The third line is the <map> tag. Note the closing tag at the bottom as well. The
content between the opening and closing tags is "nested" which causes it to indent.
Then you have the <title> and <topicref> tags. Each topicref
has an
href attribute with a directory to the .dita topic. In this example, imagine folders named 1, 2, and
3.
The forward slash character (/) indicates the .dita files are inside those folders. The leading
numbers
in the file names (e.g., 1000-, 2000-, 2005-) are the naming convention I use to order my files. It
starts with chapter number, then increments the ending number by 5 for ordering. This leaves room
for
a
few extra files to be added later in-between.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE topic PUBLIC "-//OASIS//DTD DITA Topic//EN" "topic.dtd">
<topic>
<!-- This is a comment -->
<title>Sample DITA Topic</title>
<body>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<ol>
<li>
<p>First ordered step.</p>
</li>
<li>
<p>Second ordered step.</p>
</li>
<li>
<p>Third ordered step.</p>
</li>
</ol>
<ul>
<li>
<p>First unordered list item.</p>
</li>
<li>
<p>Second unordered list item.</p>
</li>
<li>
<p>Third unordered list item.</p>
</li>
</ul>
<fig>
<title>Sample Image</title>
<image href="images/sample-image.png" align="center"/>
</fig>
<note type="warning">This is a warning.</note>
<note type="caution">This is a caution.</note>
<note>This is a note.</note>
<simpletable>
<sthead>
<stentry>This is the first column header</stentry>
<stentry>This is the second column header</stentry>
</sthead>
<strow>
<stentry>First row, first column cell</stentry>
<stentry>First row, second column cell</stentry>
</strow>
<strow>
<stentry>Second row, first column cell</stentry>
<stentry>Second row, second column cell</stentry>
</strow>
</simpletable>
<table>
<title>Sample Table</title>
<tgroup cols="2">
<colspec colname="c1" colwidth="1*"/>
<colspec colname="c2" colwidth="2*"/>
<thead>
<row>
<entry>This is the first column header</entry>
<entry>This is the second column header</entry>
</row>
</thead>
<tbody>
<row>
<entry>First row, first column cell</entry>
<entry>First row, second column cell</entry>
</row>
<row>
<entry>Second row, first column cell</entry>
<entry>Second row, second column cell</entry>
</row>
</tbody>
</tgroup>
</table>
</body>
</topic>
The first line is the XML declaration. It declares the file as XML and is always the same even for non-DITA XML files.
The second line declares the DTD for topic, which is topic.dtd.
The third line is the <topic> tag. Note the closing tag at the bottom as well.
The
content between the opening and closing tags is "nested" which causes it to indent.
The fourth line is a comment. The character data in a comment will not display in the output.
Then you have the <title> and <body> tags. The title of a topic
will appear in a table of contents or whatever other method of navigation. The body tag is merely a
container for everything else; again, note the closing tag at the bottom as well.
Then you have <p> and <ol> and <ul>. These
stand for paragraph, ordered list, and unordered list, respectively. You can
nest lists inside of each other, too. To do this, position the nested list after the paragraph
inside a list item.
Then you have <fig>. It has its own title and an image. You can have more than one
image inside one figure. Notice that, since the image tag doesn't have character data, it doesn't
need both opening and closing tags; it just ends with />
Then you have <note> for warnings, cautions, and notes. Set the kind with the type
attribute, like <note type="warning">. DITA 1.3 also has
<hazardstatement> for full safety messages with a signal word, a hazard symbol,
and how to avoid the hazard.
Then you have <simpletable>. Take a look at the general structure. Notice you
can't give a simple table a title in DITA 1.3, nor can you merge cells. If you want a table with a
caption or merged cells, use <table>.
Then you have <table>. Unlike a simpletable, a <table> can have
its own
<title> which becomes its table caption. The <tgroup> tag says
how many columns the table has,
and each <colspec> sets a column's relative width (here, the second column is
twice as wide as the first). Header rows go in <thead>, body rows go in
<tbody>, and each cell is an <entry>.
Example: MentorshipAsset7_Dita.dita (Google Drive). To save it, select the Download button at the top of the preview.
Using the example and what you've learned about DITA tags, restructure the software procedure you wrote for Portfolio Item 1 as DITA code. If you prefer, you can write a new procedure instead.
When you're ready, share the file with me through Google Drive (with comment access) or send it by email, and I'll add my feedback as comments.
This is an advanced chapter on publishing DITA to Word with free tools. Read Lesson 10 (DITA) first, and only if publishing is part of your goals.
I am writing this from a Windows perspective. Where the steps differ on a Mac, select the macOS tab.
This lesson uses the com.elovirta.ooxml plugin. As of this writing, the last major update was in 2020 (see its releases page). It works well for me but may not be the most modern free tool.
DITA OT runs on Java, so install Java first. DITA OT 4.x needs Java 17 or later. The free Temurin version from adoptium.net works well.
java -version. The Java version displays.java -version. The Java version displays.Download the DITA OT here: dita-ot.org
Info about the com.elovirta.ooxml plugin is available here: github.com/jelovirt/com.elovirta.ooxml
To install the plugin, use this command: dita install com.elovirta.ooxml
Before that will work, though, I believe you'll need to add your dita install's bin folder to your path environment variable:
nano ~/.zshrc. The nano text editor opens your shell
settings file.export PATH="$PATH:/Users/yourname/dita-ot/bin"dita version.If you're having trouble, let me know.
Keep in mind this is NOT an app; rather, it is a toolkit for developing functionality yourself based on pre-built templates. As for the functionality, it has integration with OxygenXML Editor and seems to be included with it, which simplifies the "transformation scenario" somewhat. But, since that is a paid software, I'll show you how to use the DITA OT to transform your dita code into an MS Word file (.docx) without any paid software.
After installing the DITA OT and "com.elovirta.ooxml" plugin, navigate to plugins > com.elovirta.ooxml > docx > word.
The files I recommend checking out here are:
Take a look at lines containing xsl:template match. This is XSLT code that defines a
chunk of transformation logic.
First look at
<xsl:template match="*[contains(@class, ' map/map ')]" mode="root">.
As you can see, this is where the transformation begins by targeting <map>
(the outermost tag of a
.ditamap file). This block of code pulls in the contents of template matches below (such as
"cover" and "body") via xsl:apply-templates.
Those
template matches are defined below.
Next, take a look at the various tags you see that begin with w:. This is Office
Open XML (OOXML).
| Tag | Name | Description |
|---|---|---|
| w:document | Document | Root element of a WordprocessingML document. |
| w:body | Body | Contains the main document content. |
| w:p | Paragraph | Represents a paragraph. |
| w:pPr | Paragraph Properties | Formatting and layout properties for a paragraph. |
| w:r | Run | A region of text with the same formatting. |
| w:rPr | Run Properties | Formatting properties for a run (font, size, bold, etc.). |
| w:t | Text | The actual text content inside a run. |
| w:br | Line Break | Forces a line break within a paragraph. |
| w:sectPr | Section Properties | Defines section-level settings like page size and margins. |
| w:pgSz | Page Size | Specifies the width, height, and orientation of the page. |
| w:headerReference | Header Reference | Links a section to a header part. The named r:id attributes are defined inside com.elovirta.ooxml-master > resources > Normal.docx and are accessible only by converting it to .zip and inspecting its contents. |
| w:footerReference | Footer Reference | Links a section to a footer part. The named r:id attributes are defined inside com.elovirta.ooxml-master > resources > Normal.docx and are accessible only by converting it to .zip and inspecting its contents. |
I'll try to describe how OOXML works... please look at the code inside the template match blocks and see if you understand what I'm saying:
<w:p>) begin with a Paragraph Properties block
(<w:pPr>).<w:r>). Runs begin with a Run Properties
block (<w:rPr>).<w:t>). For the text, the default formatting
will be the paragraph
properties, and the run properties override the paragraph properties
whenever they conflict.<w:sectPr>) go at the END / the BOTTOM of a template
match. This block of
code defines the page size, headers, and footers of the content ABOVE it.<w:sz w:val="24">) is recorded in half-points:
<w:rPr><w:sz w:val="24"/></w:rPr> is describing a
12-point font.
<w:pgSz>) defines the page size like
<w:pgSz w:w="12240" w:h="15840"/> ... these values are "twentieth
of an Imperial point" values (or "twips"). 1440 twips = 1 inch. For a landscape
section, swap the width and height and add the orientation attribute:
<w:pgSz w:w="15840" w:h="12240" w:orient="landscape"/>. You need
both. The numbers set the page's actual shape, and w:orient tells Word and printers
to treat it as landscape. Without w:orient, some printers and converters handle the
page as portrait.
The order in which templates are applied within
<xsl:template match="*[contains(@class, ' map/map ')]" mode="root">
determines
the whole content of the Word file export. That is where everything comes from; editing the root
gives you immediate control of your transformation.
The mode "cover" defines the "front matter" of the document.
The mode "toc" defines the table of contents. That one is actually defined in document.toc.xsl
where you can look for a <xsl:value-of> line to enter your table of contents
field code.
The mode "body" defines all topics. The template match implements logic from document.topic.xsl.
This is where you can customize your document a lot. You can add your own processing
instructions and define what they do. A processing instruction, like <?tab?>,
isn't a DITA tag: it's a separate kind of XML markup that passes an instruction to whatever tool
processes the file.
You can make new templates and modes here as well. I made a new one called "end" that adds a few extra pages after the body of the document.
document.topic.xsl handles the transformation of each DITA
<topic> and its children into paragraphs, headings, lists,
images, and other body elements.
Try searching for @class, ' topic/ and see if you recognize what the template
matches and other code is doing. The first one to be processed is
<xsl:template match="*[contains(@class, ' topic/topic ')]"> which is the
root template for every topic.
Key things you'll see here:
topic/title)
<topic/p> becomes a
<w:p> with <w:r> runs inside for text, bold,
italic, etc. (using modes like "inline-style" or "block-style")
Here are some processing instructions I made and use frequently.
In your .dita, with processing instructions, you write it in like <?tab?>. The
ones whose content is a run (e.g., the tab and horizontal line ones below) must be placed inside
a para
<p> or they won't
work. That's because the processing instruction inserts it literally, without doing anything
else under the hood to fix it for you, and runs need to be inside paragraphs.
<xsl:template match="processing-instruction('tab')">
<w:r>
<w:tab/>
</w:r>
</xsl:template>
<xsl:template match="processing-instruction('horizontal-line')">
<w:r>
<w:pict>
<xsl:choose>
<xsl:when test="ancestor::topic[1][@outputclass = 'portrait']">
<v:rect style="width:6.5in;height:1pt" o:hralign="center" o:hrstd="t" o:hrnoshade="t"
o:hr="t" fillcolor="black [3213]" stroked="f"/>
</xsl:when>
<xsl:when test="ancestor::troubleshooting[1][@outputclass = 'portrait']">
<v:rect style="width:6.5in;height:1pt" o:hralign="center" o:hrstd="t" o:hrnoshade="t"
o:hr="t" fillcolor="black [3213]" stroked="f"/>
</xsl:when>
<xsl:when test="ancestor::topic[1][@outputclass = 'landscape']">
<v:rect style="width:9in;height:1pt" o:hralign="center" o:hrstd="t" o:hrnoshade="t"
o:hr="t" fillcolor="black [3213]" stroked="f"/>
</xsl:when>
<xsl:when test="ancestor::troubleshooting[1][@outputclass = 'landscape']">
<v:rect style="width:9in;height:1pt" o:hralign="center" o:hrstd="t" o:hrnoshade="t"
o:hr="t" fillcolor="black [3213]" stroked="f"/>
</xsl:when>
<xsl:otherwise>
<v:rect style="width:468pt;height:1pt" o:hralign="center" o:hrstd="t" o:hrnoshade="t"
o:hr="t" fillcolor="black [3213]" stroked="f"/>
</xsl:otherwise>
</xsl:choose>
</w:pict>
</w:r>
</xsl:template>
<xsl:template match="processing-instruction('page-break')">
<w:r>
<w:br w:type="page"/>
</w:r>
</xsl:template>
Change the file extension of this file to .zip to inspect and modify its contents. When asked if you want to save a backup, always say no.
When you're done modifying Normal.zip, always change it back to Normal.docx or it won't work.
Also, never open this file in Word itself, especially with autosave turned on. Doing this will scramble and delete anything you have customized. I recommend keeping backups here in a folder.
On a Mac, double-clicking Normal.zip extracts it to a folder instead of opening it. Edit the files
in that folder. Don't use Finder's Compress to put it back together, because it
adds hidden files and an extra folder level that can break the file. Instead, open Terminal in
the extracted folder and enter
zip -r ../Normal.docx . -x ".*" -x "__MACOSX/*", then copy the new Normal.docx
back into the plugin's resources folder.
This Word file contains the header and footer information. It links them via named ids to the
w:sectPr
parts of document.root.xsl, specifically the r:id attributes of
w:headerReference and
w:footerReference.
The pipeline is like this:
<w:headerReference w:type="default" r:id="rId8"/>.
<Relationship Id="rId8" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/>
This same method also applies for images you wish to implement outside of the document body. For example, if you want to add a logo to the cover page, the .png file goes in Normal.docx > media and similarly has its own relationship id.
The OOXML for the image, then, in document.root.xsl is something like this:
Look for this: r:embed="imageLogo"
THAT is the id that traces to _rels.
<w:drawing>
<wp:inline
xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"
xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"
xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">
<wp:extent cx="1143000" cy="1143000"/>
<wp:docPr id="1" name="imageLogo"/>
<a:graphic>
<a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">
<pic:pic>
<pic:nvPicPr>
<pic:cNvPr id="0" name="imageLogo"/>
<pic:cNvPicPr/>
</pic:nvPicPr>
<pic:blipFill>
<a:blip r:embed="imageLogo"/>
<a:stretch>
<a:fillRect/>
</a:stretch>
</pic:blipFill>
<pic:spPr>
<a:xfrm>
<a:off x="0" y="0"/>
<a:ext cx="1143000" cy="1143000"/>
</a:xfrm>
<a:prstGeom prst="rect">
<a:avLst/>
</a:prstGeom>
</pic:spPr>
</pic:pic>
</a:graphicData>
</a:graphic>
</wp:inline>
</w:drawing>
This only works if you have dita install's bin folder added to the system environment path variable.
This set of console scripts tells you if it is working: dita version and
dita plugins and dita transtypes
These are the commands for DITA-OT 4.x. Older versions (3.x) use dita --version,
dita --plugins, dita --transtypes, and dita --install.
This console script executes the transformation procedure:
dita -i yourmap.ditamap -f docx -o output-folder
Field codes are a Word power-user feature. They're handy for long manuals but not required for the Core Course.
In Microsoft Word, field codes display contextual information that can be updated over time, such as a table of contents, or specific types of variables such as page numbers and dates.
Important: A newly created field code must be updated at least once before its output becomes visible. Otherwise it appears blank.
On a Mac, use [Command] in place of [CTRL] and [Option] in place of [ALT]: [Command] + [F9] creates a field code, [Option] + [F9] toggles field codes, and [Command] + [A] selects all. If the F keys change the volume or brightness, also hold [Fn]. To right-click, hold [Control] and click.
To toggle field codes, first click anywhere in the main document body, then press [ALT] + [F9]. The field code toggles between displaying the code and its designated output.
To create a new field code, first click where you want to place it in the main document body, then press [CTRL] + [F9]. It will initially appear blank.
To update a field code, right-click the field code and select Update Field. (You may need to right-click what initially appears to be nothing.)
{ DATE \@ "dd MMMM, yyyy" } → 02 April, 2025
{ DATE \@ "dd/MM/yy" } → 02/04/25
{ TIME \@ "h:mm AM/PM" } → 11:04 AM
{ TIME \@ "HH:mm:ss" } → 11:04:30
d = dayM = monthy = yearH = hour (24h)h = hour (12h)m = minutes = secondAM/PM = AM or PM indicator{ PAGE } → current page number
{ PAGE \* ARABIC } → 9
{ PAGE \* roman } → ix
{ NUMPAGES }
{ NUMPAGES \* ARABIC } → 42
{ NUMPAGES \* roman } → xlii
The format for this field code includes an identifier (such as Figure) and switches (such as
\n which increments the
number and \r 1 which resets the number to one). After SEQ, express the format like
this:
{ SEQ Figure \n } → 1, 2, 3…
{ SEQ Figure \r 1 } → reset to 1
The identifier doesn't display in the output. It works like an id, so more than one sequence can co-exist.
{ TOC \o "1-4" \h } → Headings 1-4 with hyperlinks
{ TOC \t "Caption,1" } → All Caption-style paragraphs at level
1
{ TOC \o "1-4" \t "TitleHowToUse,1,Appendix1,1,Appendix2,2" }
→
The table of contents contains Heading 1, Heading 2, Heading 3, and Heading 4. It also contains
all
paragraphs with the TitleHowToUse, Appendix1, and Appendix2 paragraph styles, at depth levels 1,
1,
and 2, respectively.
A paragraph with no content still has a paragraph style applied to it, so watch for blank TOC entries.
Add \* MERGEFORMAT to allow manual formatting changes to persist after updates.
Regex is a find-and-replace power tool. It can save hours on large documents, but you can be a great technical writer without it.
Regular expressions (regex) are powerful patterns that, using concise symbolic notation, greatly expand find/replace functionality. They help with bulk processing of more than one file at a time, and they can search, find, and manipulate text strings by describing specific rules or structures. Indeed this has the potential to make a time-consuming task a hundred times easier.
A simple example is (?si)\b(he|his|him|himself|she|hers|her|herself)\b. This searches
for all 8 words at the same time!
Learn more here: RegexOne interactive lessons and regex101.com tester.
Under each table, examples show a pattern, sample text with the matches underlined, and what the pattern is for.
| Token | Matches |
|---|---|
\d |
one digit (0–9) |
\w |
one word character (letter, digit, underscore) |
\s |
one whitespace character |
\D, \W, \S |
the opposite: one character that is not a digit, not a word character, or not whitespace |
. |
any character except line break |
\. |
literal period |
\ |
escape the next character |
| Pattern | What it does | Sample text |
|---|---|---|
\d\d |
Finds two digits in a row. | Torque bolts to 35 in-lb. |
\w\w\w-\d\d |
Finds part numbers shaped like three characters, a hyphen, and two digits. | Install label roll LBL-12. |
Fig\. |
Finds the abbreviation only. Without the backslash, the period matches any character, so Fig. would also match "Figu" in "Figure". |
See Fig. 3 and Figure 4. |
\S+@\S+ |
Finds email addresses: non-space characters on both sides of an @. | Email support@example.com for help. |
| Token | Meaning |
|---|---|
+ |
1 or more |
* |
0 or more |
? |
0 or 1 |
{3} |
exactly 3 |
{2,4} |
2 to 4 |
{3,} |
3 or more |
*?, +? |
lazy: match as little as possible (e.g. .*?) |
| Pattern | What it does | Sample text |
|---|---|---|
\s{2,} |
Finds two or more spaces in a row. Replace with one space to clean up spacing. | Remove the cover. Set it aside. |
colou?r |
Finds both spellings: the u is optional. |
color and colour |
\d{3}-\d{4} |
Finds phone numbers shaped like 555-0142. | Call 555-0142 for support. |
".*" |
Greedy: runs from the first quotation mark to the last one. | Select "Save" and then "Close". |
".*?" |
Lazy: stops at the first closing quotation mark, so each quoted label matches separately. | Select "Save" and then "Close". |
| Operator | Effect |
|---|---|
| |
OR |
(…) |
capturing group (use \1, \2… in replacement) |
(?:…) |
non-capturing group |
| Pattern | What it does | Sample text |
|---|---|---|
warning|caution |
Finds either word. | Read the warning and caution first. |
(Fig|Figure)\s(\d+)Replace with: Figure \2 |
Makes figure references consistent. \2 puts back the number from the second group. |
Before: See Fig 3 and Figure 4. After: See Figure 3 and Figure 4. |
(\w+), (\w+)Replace with: \2 \1 |
Swaps last name, first name. | Before: Smith, Alex After: Alex Smith |
(?:Step|Task) (\d+)Replace with: Step \1 |
The first group doesn't capture, so the number is \1, not \2. |
Before: Task 4 After: Step 4 |
| Pattern | Matches |
|---|---|
[abc] |
a, b, or c |
[a-z] |
any lowercase letter |
[^0-9] |
anything not a digit |
| Pattern | What it does | Sample text |
|---|---|---|
[A-Z]{2,} |
Finds acronyms: two or more capital letters in a row. Turn on Match Case, or it also matches lowercase words. | Check the LED on the UPS. |
gr[ae]y |
Finds both spellings. | gray or grey |
[“”‘’] |
Finds curly quotation marks, so you can make them consistent with straight ones (or the other way around). | Select “Save”. |
[^\x00-\x7F] |
Finds any non-ASCII character, like symbols and dashes that may not survive a conversion. | Turn the knob 90° – slowly. |
| Anchor | Meaning |
|---|---|
^ |
start of a line (in most text editors) |
$ |
end of a line (in most text editors) |
\b |
word boundary |
| Pattern | What it does | Sample text |
|---|---|---|
^\d+\.\s |
Finds typed step numbers at the start of a line. Replace with nothing to remove them before applying real numbering. | 1. Remove the cover. |
\s+$ |
Finds extra spaces at the end of a line. | Close the cover. |
in |
Without boundaries, it also matches inside other words. | Put the pin in the slot. |
\bin\b |
With word boundaries, it matches only the whole word. | Put the pin in the slot. |
| Flag | Effect |
|---|---|
(?i) |
ignore case |
(?s) |
. also matches line breaks |
(?m) |
^ and $ match at every line (many editors do this already) |
| Pattern | What it does | Sample text |
|---|---|---|
(?i)warning |
Finds the word in any capitalization. | WARNING, Warning, and warning |
(?s)<note>.*?</note> |
Finds the whole element, even across line breaks. | A note element whose text wraps onto several lines. |
Flags go at the very start of the pattern. The (?si) in the summary example turns on
two flags at once. Some tools, like Visual Studio Code, don't accept flags in the pattern; use
the tool's Match Case button instead.
<title>\d+\.\s+(.*?)</title> →
<title>\1</title>[A-Z](?![A-Z])[^\.!?]*?,[^\.!?]+?,[^\.!?]+?,[^\.!?]+?,[^\.!?]*?[\.!?](?:\s+|$)\b(\w+)\s+\1\bYou do not need to learn Python. Technical writing jobs don't require programming. This chapter only shows how to run a ready-made script that automates a tedious task (listing every acronym in a document). Reading the code is optional, and so is this whole chapter.
Python scripts can automate tasks, turning days of work into a few seconds. I invite you to consider making your own scripts after exploring what the libraries are capable of.
Install Python for free with the Python install manager, from the Microsoft Store or from python.org. It installs the latest Python and adds an app to the Start menu for opening the Python console.
Download the macOS installer for free from python.org and run it. This installer includes tkinter, which the example script needs for its window, and it adds an app called IDLE for opening the Python console.
Use the python.org installer rather than the Python that macOS or Homebrew provides. Those versions may be missing tkinter or block installing libraries.
By installing libraries onto your computer via the terminal and importing them at the top of your script, you greatly expand the scripts' capabilities.
The libraries are "dependencies"; if a script uses functions from a library that is not imported first, or is imported but not yet installed, the script will fail. Therefore, remember that you need to both install AND import the Python libraries you are using.
Here is a list of libraries I used in my example script below, which finds which acronyms from a key spreadsheet appear in a .docx or .pdf file:
| Library / Import | Description | Needs installing? |
|---|---|---|
import os |
Provides the essential Operating System interface to navigate directories and create files in them. | No |
import re |
Provides tools for working with regular expressions (match, search, replace, split, etc.) | No |
import unicodedata |
Provides the essential Unicode database access (normalization, decomposition, character properties, etc.) | No |
import zipfile |
Opens .zip archives. A .docx file is really a .zip of XML files, so this is how the script gets inside it. | No |
import xml.etree.ElementTree as ET |
Reads XML. The script uses it to pull the text out of the XML files inside the .docx. | No |
import tkinter as tk |
Provides tools for building a software GUI elements (windows, widgets, dialogs). | No |
from tkinter import filedialog, messagebox |
Imports tkinter submodules: file open/save dialogs + message/pop-up boxes | No |
import pandas as pd |
Provides tools for working with data manipulation and analysis (DataFrames, Series, CSV/Excel, groupby, merge, etc.) | Yes (pandas) |
engine="openpyxl" |
Creates, reads, modifies and saves Microsoft Excel (.xlsx) files. Note this did not require an import because pandas does it by calling an engine. | Yes (openpyxl) |
from pypdf import PdfReader |
Reads, modifies, and extracts text from PDF files. The script also accepts the older PyPDF2 if that is what's installed. | Yes (pypdf) |
Script files: Acronym Parser folder (Google Drive). To save it, select Download all at the top of the folder. Drive downloads it as a .zip file; extract it before you begin.
python -m pip install pandaspython -m pip install openpyxlpython -m pip install pypdfpython3 -m pip install pandaspython3 -m pip install openpyxlpython3 -m pip install pypdfOn a Mac, the command is python3, not python.
import osos.chdir(r"XXX") where XXX is the directory to the folder containing
main.py, for example
C:\Users\yourname\Documents\Acronym Parser v3. (To copy a folder's
path, right-click on the folder in File Explorer and select Copy as
path.)
exec(open("main.py").read())import osos.chdir("XXX") where XXX is the directory to the folder containing
main.py, for example /Users/yourname/Documents/Acronym Parser v3. (To
copy a folder's path, hold [Option], right-click on the folder in
Finder, and select Copy "folder" as Pathname.)exec(open("main.py").read())"""
Acronym Parser
==============
Checks a .docx or .pdf document against a key spreadsheet of acronyms and
reports which acronyms from the key actually appear in the document.
Inputs
* Key spreadsheet (.xlsx) - acronym in column A, definition in column B
* Document (.docx or .pdf)
* Output folder
Output
* output_acronyms_list.xlsx - one row per acronym found in the document
(column A = acronym, column B = definition), sorted A-Z
How the script is organized
1. read_acronym() loads the key spreadsheet into a dictionary
2. build_lookup() prepares every spelling we will accept for each acronym
3. read_document() pulls all of the text out of the .docx or .pdf
4. find_acronyms() checks the document text against the lookup
5. run_extraction() runs steps 1-4 and writes the output file
6. AcronymApp the small Tkinter window that calls run_extraction()
Requirements: pip install pandas openpyxl pypdf (PyPDF2 also works)
"""
import os
import re
import unicodedata
import zipfile
import xml.etree.ElementTree as ET
import tkinter as tk
from tkinter import filedialog, messagebox
import pandas as pd
# ---------------------------------------------------------------------------
# Settings
# ---------------------------------------------------------------------------
# A "word" is a run of letters/digits plus / . & - so that things like
# "AI/ML", "U.S.", "O&M" and "Wi-Fi" stay in one piece.
WORD_PATTERN = re.compile(r"\b[\w/.&-]+\b")
# If the first row of the key sheet says one of these, it is a header, not data.
HEADER_WORDS = {"acronym", "acronyms", "abbreviation", "abbreviations",
"term", "terms", "initialism"}
# Longest key (in words) that we will look for, e.g. 8 words.
MAX_WORDS_IN_KEY = 8
# XML namespaces used inside .docx files.
W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
A = "{http://schemas.openxmlformats.org/drawingml/2006/main}"
C = "{http://schemas.openxmlformats.org/drawingml/2006/chart}"
WP = "{http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing}"
# Which files inside the .docx zip hold which kind of text.
DOCX_TEXT_PARTS = re.compile(
r"^word/(document|header\d*|footer\d*|footnotes|endnotes|comments"
r"|glossary/document)\.xml$|^word/diagrams/data\d*\.xml$")
DOCX_CHART_PARTS = re.compile(r"^word/charts/chart\d+\.xml$")
DOCX_METADATA_PARTS = re.compile(
r"^(docProps/(core|app|custom)|customXml/item\d+)\.xml$")
# ---------------------------------------------------------------------------
# Text helpers
# ---------------------------------------------------------------------------
def normalize_text(text: str) -> str:
"""Standardize slashes and collapse extra whitespace."""
if not text:
return text
# Turn look-alike Unicode slashes into a normal forward slash.
text = unicodedata.normalize("NFKC", text).replace("⁄", "/").replace("∕", "/")
# Collapse tabs, newlines and repeated spaces into single spaces.
return " ".join(text.split())
def clean_word(word: str) -> str:
"""Remove the punctuation we ignore when comparing, so 'U.S.' == 'US'."""
return re.sub(r"[.,()]", "", word)
def normalize_key(key: str) -> str:
"""Put a spreadsheet key into the same form as the words we pull from the
document, so the two can be compared directly."""
words = (clean_word(w) for w in normalize_text(key).split())
return " ".join(w for w in words if w)
def split_into_words(text: str) -> list:
"""Break a piece of text into clean words."""
words = (clean_word(w) for w in WORD_PATTERN.findall(normalize_text(text)))
return [w for w in words if w]
def ngram_generator(words: list, n: int):
"""Yield every run of n neighbouring words, joined by spaces.
With n=2 and ["Air", "Force", "One"] this yields "Air Force", "Force One".
This is how multi-word entries in the key (like "Air Force") get matched.
"""
for i in range(len(words) - n + 1):
yield " ".join(words[i:i + n])
# ---------------------------------------------------------------------------
# Step 1: read the key spreadsheet
# ---------------------------------------------------------------------------
def read_acronym(file_path: str) -> dict:
"""Return {acronym: definition} from columns A and B of every sheet.
Blank rows are skipped, a header row such as "Acronym | Definition" is
ignored, and an acronym with no definition gets an empty definition.
"""
# sheet_name=None -> read every sheet; dtype=str -> never turn "007" into 7.
sheets = pd.read_excel(file_path, engine="openpyxl", header=None,
sheet_name=None, dtype=str)
data_dict = {}
for df in sheets.values():
if df.shape[1] == 0:
continue
for row_number in range(len(df)):
key = df.iat[row_number, 0]
if pd.isna(key) or not str(key).strip():
continue # blank row
key = str(key).strip()
if row_number == 0 and key.lower() in HEADER_WORDS:
continue # header row
definition = ""
if df.shape[1] > 1 and not pd.isna(df.iat[row_number, 1]):
definition = str(df.iat[row_number, 1]).strip()
# First entry wins, unless it had no definition and this one does.
if key not in data_dict or not data_dict[key]:
data_dict[key] = definition
return data_dict
# ---------------------------------------------------------------------------
# Step 2: decide which spellings count as a match
# ---------------------------------------------------------------------------
def build_lookup(acronym_dict: dict):
"""Build {accepted spelling: key as written in the spreadsheet}.
Every key is accepted as written, plus its plural forms (key + "s" and
key + "es"). Real keys are added first, so a plural can never overwrite a
real entry (for example if the sheet has both "PC" and "PCs").
Returns the lookup and the number of words in the longest key.
"""
lookup = {}
for key in acronym_dict:
name = normalize_key(key)
if name:
lookup[name] = key
for key in acronym_dict:
name = normalize_key(key)
if name:
lookup.setdefault(name + "s", key)
lookup.setdefault(name + "es", key)
longest = max((len(name.split()) for name in lookup), default=1)
return lookup, min(longest, MAX_WORDS_IN_KEY)
# ---------------------------------------------------------------------------
# Step 3: read the document
#
# Both readers return a list of "chunks" - strings such as one paragraph, one
# table cell, one footnote or one metadata value. Keeping them separate stops
# the last word of one paragraph from being glued to the first word of the
# next when we look for multi-word acronyms.
# ---------------------------------------------------------------------------
def paragraph_chunks(root) -> list:
"""Return the text of every paragraph in an XML tree (Word or DrawingML)."""
chunks = []
for paragraph in root.iter():
if paragraph.tag not in (W + "p", A + "p"):
continue
parts = []
for el in paragraph.iter():
if el.tag in (W + "t", A + "t"): # a run of text
parts.append(el.text or "")
elif el.tag in (W + "tab", W + "br", W + "cr"):
parts.append(" ") # tabs/line breaks = space
text = "".join(parts).strip()
if text:
chunks.append(text)
return chunks
def leaf_chunks(root) -> list:
"""Return the text of every element that has no child elements."""
return [el.text.strip() for el in root.iter()
if len(el) == 0 and el.text and el.text.strip()]
def read_docx(doc_file: str) -> list:
"""Read a .docx by opening it as the zip archive of XML files it really is.
Going straight to the XML (instead of a library like python-docx) means we
also get text that libraries skip: text boxes, nested tables, content
controls, footnotes, endnotes, comments, picture alt text, chart and SmartArt
text, document properties, custom properties and document variables.
Deleted text from tracked changes is ignored; inserted text is included.
"""
chunks = []
with zipfile.ZipFile(doc_file) as z:
for name in z.namelist():
if not name.endswith(".xml"):
continue
try:
root = ET.fromstring(z.read(name))
except ET.ParseError:
continue # skip a damaged part
if DOCX_TEXT_PARTS.match(name):
# body, headers, footers, footnotes, comments, SmartArt...
chunks.extend(paragraph_chunks(root))
# alt text / titles on pictures and shapes
for el in root.iter(WP + "docPr"):
chunks.extend(el.get(a) for a in ("title", "descr") if el.get(a))
elif DOCX_CHART_PARTS.match(name):
# chart titles (a:t) and category/series names (c:v)
chunks.extend(el.text for el in root.iter()
if el.tag in (A + "t", C + "v") and el.text)
elif DOCX_METADATA_PARTS.match(name):
chunks.extend(leaf_chunks(root))
elif name == "word/settings.xml":
# "Document variables" are stored as attributes
chunks.extend(el.get(W + "val") for el in root.iter(W + "docVar")
if el.get(W + "val"))
return chunks
def get_pdf_reader():
"""Return the PdfReader class from pypdf, or from PyPDF2 if that is what
is installed."""
try:
from pypdf import PdfReader
except ImportError:
try:
from PyPDF2 import PdfReader
except ImportError:
raise ImportError("Reading PDFs needs the pypdf package.\n"
"Install it with: pip install pypdf")
return PdfReader
def bookmark_titles(outline) -> list:
"""Return the titles of all bookmarks. Sub-bookmarks arrive as nested lists."""
titles = []
for item in outline:
if isinstance(item, list):
titles.extend(bookmark_titles(item))
elif getattr(item, "title", None):
titles.append(str(item.title))
return titles
def read_pdf(doc_file: str) -> list:
"""Read the text of every page, plus comments, form fields and metadata."""
PdfReader = get_pdf_reader()
reader = PdfReader(doc_file)
if reader.is_encrypted:
try:
unlocked = reader.decrypt("") # try an empty password
except Exception:
unlocked = 0
if not unlocked:
raise ValueError("This PDF is password-protected.")
chunks = []
for page in reader.pages:
text = page.extract_text()
if text:
chunks.append(text)
# Comments / sticky notes on the page. These extras are optional, so a
# problem with one of them must never stop the whole run.
try:
for annotation in page.get("/Annots") or []:
note = annotation.get_object().get("/Contents")
if isinstance(note, str) and note.strip():
chunks.append(note)
except Exception:
pass
try: # filled-in form fields
for field in (reader.get_fields() or {}).values():
value = field.get("/V")
if isinstance(value, str) and value.strip():
chunks.append(value)
except Exception:
pass
try: # bookmarks (outline)
chunks.extend(bookmark_titles(reader.outline))
except Exception:
pass
try: # title, author, etc.
for value in (reader.metadata or {}).values():
if isinstance(value, str) and value.strip():
chunks.append(value)
except Exception:
pass
return chunks
def read_document(doc_file: str) -> list:
"""Return a list of text chunks from a .docx or .pdf file."""
extension = os.path.splitext(doc_file)[1].lower()
if extension == ".docx":
try:
return read_docx(doc_file)
except zipfile.BadZipFile:
raise ValueError(f"{doc_file} is not a valid .docx file.")
if extension == ".pdf":
try:
return read_pdf(doc_file)
except (ImportError, ValueError):
raise
except Exception as e:
raise Exception(f"Error reading PDF file {doc_file}: {str(e)}")
raise ValueError(f"Unsupported file extension {extension}. "
"Only .docx and .pdf are supported.")
# ---------------------------------------------------------------------------
# Step 4: find the acronyms
# ---------------------------------------------------------------------------
def find_acronyms(chunks: list, lookup: dict, max_words: int) -> set:
"""Return the set of keys (as written in the spreadsheet) that appear in
the document text."""
found = set()
for chunk in chunks:
words = split_into_words(chunk)
for n in range(1, max_words + 1):
for phrase in ngram_generator(words, n):
# Looking up in a dictionary is instant; searching a list for
# every key would get slower and slower on big documents.
if phrase in lookup:
found.add(lookup[phrase])
return found
# ---------------------------------------------------------------------------
# Step 5: run everything
# ---------------------------------------------------------------------------
def check_readable(path: str, label: str):
"""Raise a clear error if a file is missing or cannot be opened."""
if not os.path.exists(path):
raise FileNotFoundError(f"{label} {path} not found")
if not os.path.isfile(path):
raise FileNotFoundError(f"{path} exists but is not a file")
if not os.access(path, os.R_OK):
raise PermissionError(f"Cannot read {path} due to permissions")
def run_extraction(acronym_file: str, doc_file: str, output_dir: str) -> str:
print("---- Program Started ----")
try:
check_readable(acronym_file, "Acronym file")
check_readable(doc_file, "Document file")
# makedirs also creates any missing parent folders.
os.makedirs(output_dir, exist_ok=True)
if not os.access(output_dir, os.W_OK):
raise PermissionError(f"Cannot write to directory {output_dir}")
acronym_dict = read_acronym(acronym_file)
print(f"Excel read successfully: {acronym_file} ({len(acronym_dict)} entries)")
lookup, max_words = build_lookup(acronym_dict)
chunks = read_document(doc_file)
print(f"Document read successfully: {doc_file}")
found = find_acronyms(chunks, lookup, max_words)
found_sorted = sorted(found, key=str.casefold)
output_df = pd.DataFrame({
"word": found_sorted,
"acronym": [acronym_dict[key] for key in found_sorted],
})
output_file = os.path.join(output_dir, "output_acronyms_list.xlsx")
try:
output_df.to_excel(output_file, index=False, header=None)
except PermissionError:
raise PermissionError(f"Cannot write to file {output_file} "
"(is it open in Excel?)")
print("---- Output Generated Successfully ----")
return (f"Found {len(found_sorted)} acronym(s) from the key.\n"
f"Output generated successfully at:\n{output_file}")
except Exception as e:
print(f"---- Error Occurred: {e} ----")
raise
# ---------------------------------------------------------------------------
# Step 6: the window
# ---------------------------------------------------------------------------
class AcronymApp:
def __init__(self, root):
self.root = root
self.root.title("Acronym Extractor")
self.root.geometry("600x400")
# Variables that hold the paths the user picks.
self.acronym_file = tk.StringVar()
self.doc_file = tk.StringVar()
self.output_dir = tk.StringVar()
tk.Label(root, text="Select Acronym Excel File (.xlsx):").pack(pady=10)
tk.Entry(root, textvariable=self.acronym_file, width=50).pack()
tk.Button(root, text="Browse", command=self.browse_acronym_file).pack(pady=5)
tk.Label(root, text="Select Document File (.docx or .pdf):").pack(pady=10)
tk.Entry(root, textvariable=self.doc_file, width=50).pack()
tk.Button(root, text="Browse", command=self.browse_doc_file).pack(pady=5)
tk.Label(root, text="Select Output Directory:").pack(pady=10)
tk.Entry(root, textvariable=self.output_dir, width=50).pack()
tk.Button(root, text="Browse", command=self.browse_output_dir).pack(pady=5)
self.run_button = tk.Button(root, text="Run Acronym Extraction",
command=self.run_extraction)
self.run_button.pack(pady=20)
def browse_acronym_file(self):
# Only .xlsx: the reader (openpyxl) cannot open the older .xls format.
file_path = filedialog.askopenfilename(filetypes=[("Excel files", "*.xlsx")])
if file_path:
self.acronym_file.set(file_path)
def browse_doc_file(self):
file_path = filedialog.askopenfilename(filetypes=[("Document files", "*.docx *.pdf")])
if file_path:
self.doc_file.set(file_path)
# Convenience: default the output folder to the document's folder.
if not self.output_dir.get():
self.output_dir.set(os.path.dirname(file_path))
def browse_output_dir(self):
dir_path = filedialog.askdirectory()
if dir_path:
self.output_dir.set(dir_path)
def run_extraction(self):
acronym_file = self.acronym_file.get().strip()
doc_file = self.doc_file.get().strip()
output_dir = self.output_dir.get().strip()
if not acronym_file or not doc_file or not output_dir:
messagebox.showerror("Error", "Please select all required files and directory.")
return
# The window freezes while we work, so show that something is happening.
self.run_button.config(state="disabled", text="Working...")
self.root.config(cursor="watch")
self.root.update()
try:
message = run_extraction(acronym_file, doc_file, output_dir)
messagebox.showinfo("Success", message)
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
finally:
self.root.config(cursor="")
self.run_button.config(state="normal", text="Run Acronym Extraction")
def main():
root = tk.Tk()
AcronymApp(root)
root.mainloop()
if __name__ == "__main__":
main()
You do not need to understand this. It's included for transparency, so you can see what the script does before you run it.
if __name__ == "__main__":, which
calls def main to open the
window. When the user selects Run Acronym Extraction, the window's run_extraction
method
checks that all three fields are filled in, changes the button to "Working..." so the user knows
something is happening, then calls the main def run_extraction function.
if __name__ == "__main__":
main()
def run_extraction(self):
acronym_file = self.acronym_file.get().strip()
doc_file = self.doc_file.get().strip()
output_dir = self.output_dir.get().strip()
if not acronym_file or not doc_file or not output_dir:
messagebox.showerror("Error", "Please select all required files and directory.")
return
# The window freezes while we work, so show that something is happening.
self.run_button.config(state="disabled", text="Working...")
self.root.config(cursor="watch")
self.root.update()
try:
message = run_extraction(acronym_file, doc_file, output_dir)
messagebox.showinfo("Success", message)
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
finally:
self.root.config(cursor="")
self.run_button.config(state="normal", text="Run Acronym Extraction")
def run_extraction validates that all required paths exist and are
accessible. The same three
checks run on both files through def check_readable, and the output folder is
created if it
doesn't exist yet.
def check_readable(path: str, label: str):
"""Raise a clear error if a file is missing or cannot be opened."""
if not os.path.exists(path):
raise FileNotFoundError(f"{label} {path} not found")
if not os.path.isfile(path):
raise FileNotFoundError(f"{path} exists but is not a file")
if not os.access(path, os.R_OK):
raise PermissionError(f"Cannot read {path} due to permissions")
def run_extraction(acronym_file: str, doc_file: str, output_dir: str) -> str:
print("---- Program Started ----")
try:
check_readable(acronym_file, "Acronym file")
check_readable(doc_file, "Document file")
# makedirs also creates any missing parent folders.
os.makedirs(output_dir, exist_ok=True)
if not os.access(output_dir, os.W_OK):
raise PermissionError(f"Cannot write to directory {output_dir}")
def read_acronym it "reads" (adds) the acronym Excel file's data
into a "dictionary"
(set of key-value pairs). The first column (the acronym) becomes the key, and the second column
(the definition) becomes the value. It reads every sheet in the workbook, skips blank rows and a
header row, and reads every cell as text so a value like "007" doesn't turn into the number 7.
def read_acronym(file_path: str) -> dict:
"""Return {acronym: definition} from columns A and B of every sheet.
Blank rows are skipped, a header row such as "Acronym | Definition" is
ignored, and an acronym with no definition gets an empty definition.
"""
# sheet_name=None -> read every sheet; dtype=str -> never turn "007" into 7.
sheets = pd.read_excel(file_path, engine="openpyxl", header=None,
sheet_name=None, dtype=str)
data_dict = {}
for df in sheets.values():
if df.shape[1] == 0:
continue
for row_number in range(len(df)):
key = df.iat[row_number, 0]
if pd.isna(key) or not str(key).strip():
continue # blank row
key = str(key).strip()
if row_number == 0 and key.lower() in HEADER_WORDS:
continue # header row
definition = ""
if df.shape[1] > 1 and not pd.isna(df.iat[row_number, 1]):
definition = str(df.iat[row_number, 1]).strip()
# First entry wins, unless it had no definition and this one does.
if key not in data_dict or not data_dict[key]:
data_dict[key] = definition
return data_dict
def build_lookup it lists every spelling that counts as a match:
each acronym as
written, plus its "-s" and "-es" plural variants. This way, the Acronym spreadsheet doesn't need
to
include the plural variants. Each spelling points back to the acronym as written in the
spreadsheet, so the output never needs to strip the plural endings off again. The real acronyms
are added before the plurals, so a plural can never replace a real entry (for example, if the
sheet has both "PC" and "PCs").
def build_lookup(acronym_dict: dict):
"""Build {accepted spelling: key as written in the spreadsheet}.
Every key is accepted as written, plus its plural forms (key + "s" and
key + "es"). Real keys are added first, so a plural can never overwrite a
real entry (for example if the sheet has both "PC" and "PCs").
Returns the lookup and the number of words in the longest key.
"""
lookup = {}
for key in acronym_dict:
name = normalize_key(key)
if name:
lookup[name] = key
for key in acronym_dict:
name = normalize_key(key)
if name:
lookup.setdefault(name + "s", key)
lookup.setdefault(name + "es", key)
longest = max((len(name.split()) for name in lookup), default=1)
return lookup, min(longest, MAX_WORDS_IN_KEY)
def read_document it reads the document. This step supports both
.docx and .pdf files,
and returns the text as a list of "chunks": one paragraph, table cell, footnote or other piece
of
text each. Keeping the chunks separate stops the last word of one paragraph from joining the
first
word of the next.
def read_document(doc_file: str) -> list:
"""Return a list of text chunks from a .docx or .pdf file."""
extension = os.path.splitext(doc_file)[1].lower()
if extension == ".docx":
try:
return read_docx(doc_file)
except zipfile.BadZipFile:
raise ValueError(f"{doc_file} is not a valid .docx file.")
if extension == ".pdf":
try:
return read_pdf(doc_file)
except (ImportError, ValueError):
raise
except Exception as e:
raise Exception(f"Error reading PDF file {doc_file}: {str(e)}")
raise ValueError(f"Unsupported file extension {extension}. "
"Only .docx and .pdf are supported.")
def read_docx opens the file as the .zip of XML files it really is,
instead of using a
library like python-docx. That way it also finds text the library would miss: text boxes,
footnotes, endnotes, comments, picture alt text, charts, SmartArt and document properties. For a
.pdf, def read_pdf reads the text of every page, plus comments, form fields,
bookmarks and
document properties.
def read_docx(doc_file: str) -> list:
"""Read a .docx by opening it as the zip archive of XML files it really is.
Going straight to the XML (instead of a library like python-docx) means we
also get text that libraries skip: text boxes, nested tables, content
controls, footnotes, endnotes, comments, picture alt text, chart and SmartArt
text, document properties, custom properties and document variables.
Deleted text from tracked changes is ignored; inserted text is included.
"""
chunks = []
with zipfile.ZipFile(doc_file) as z:
for name in z.namelist():
if not name.endswith(".xml"):
continue
try:
root = ET.fromstring(z.read(name))
except ET.ParseError:
continue # skip a damaged part
if DOCX_TEXT_PARTS.match(name):
# body, headers, footers, footnotes, comments, SmartArt...
chunks.extend(paragraph_chunks(root))
# alt text / titles on pictures and shapes
for el in root.iter(WP + "docPr"):
chunks.extend(el.get(a) for a in ("title", "descr") if el.get(a))
elif DOCX_CHART_PARTS.match(name):
# chart titles (a:t) and category/series names (c:v)
chunks.extend(el.text for el in root.iter()
if el.tag in (A + "t", C + "v") and el.text)
elif DOCX_METADATA_PARTS.match(name):
chunks.extend(leaf_chunks(root))
elif name == "word/settings.xml":
# "Document variables" are stored as attributes
chunks.extend(el.get(W + "val") for el in root.iter(W + "docVar")
if el.get(W + "val"))
return chunks
def ngram_generator it generates runs of neighboring words called
n-grams, to help
detect acronyms that are more than one word long. With n=2 and the words "Air Force One", it
generates "Air Force" and "Force One". Then def find_acronyms checks every single
word and
every n-gram, up to the length of the longest acronym in the spreadsheet, against the list of
accepted spellings, and records which acronyms appear.
def ngram_generator(words: list, n: int):
"""Yield every run of n neighbouring words, joined by spaces.
With n=2 and ["Air", "Force", "One"] this yields "Air Force", "Force One".
This is how multi-word entries in the key (like "Air Force") get matched.
"""
for i in range(len(words) - n + 1):
yield " ".join(words[i:i + n])
def find_acronyms(chunks: list, lookup: dict, max_words: int) -> set:
"""Return the set of keys (as written in the spreadsheet) that appear in
the document text."""
found = set()
for chunk in chunks:
words = split_into_words(chunk)
for n in range(1, max_words + 1):
for phrase in ngram_generator(words, n):
# Looking up in a dictionary is instant; searching a list for
# every key would get slower and slower on big documents.
if phrase in lookup:
found.add(lookup[phrase])
return found
found = find_acronyms(chunks, lookup, max_words)
found_sorted = sorted(found, key=str.casefold)
output_df = pd.DataFrame({
"word": found_sorted,
"acronym": [acronym_dict[key] for key in found_sorted],
})
output_file = os.path.join(output_dir, "output_acronyms_list.xlsx")
try:
output_df.to_excel(output_file, index=False, header=None)
except PermissionError:
raise PermissionError(f"Cannot write to file {output_file} "
"(is it open in Excel?)")
print("---- Output Generated Successfully ----")
return (f"Found {len(found_sorted)} acronym(s) from the key.\n"
f"Output generated successfully at:\n{output_file}")
Preparation tips for technical communication job interviews. Open this whenever an interview is coming up.
Adapted from the ATD Mentor Toolkit (pages 8-9).
How to Ace Your Next Job Interview by Robin Ryan (ATD blog) is worth reading in full. In short, she recommends:
The ATD Mentorship program representative, Laine Istvan, recommends the Farah Sharghi YouTube channel. (I haven't reviewed it myself; I'm passing along the recommendation.)
She also practices interviewing out loud with an AI voice assistant, which can point out gaps in your answers or where you could be more concise.
Some workplaces, especially in defense, have perimeter fencing, security checkpoints, and gated entrances. Consider visiting a few days early to find the main entrance, so you don't spend interview day circling the building.
Many secure buildings stay locked and require you to call a posted number or use an intercom. Allow extra time, and be ready to wait outside in whatever the weather is doing.
Choosing a school or college is a major life decision that involves balancing your wants and needs against practical realities such as cost, location, and your various unique life circumstances and challenges.
The goal is to find schools where you can thrive according to your own goals, limitations, and proclivities. Nobody else can tell you what it means to thrive, not even a mentor, because your life belongs to you and you decide what matters.
Start by reflecting on what you want to achieve and the kind of environment that will help you grow. You may move laterally a couple times before reaching the true path. That is expected and normal. As you search, try to keep an open mind and take a few steps beyond your initial assumptions before ruling out an option. You can ask others if you have a question about something you discovered.
Evaluate the list below. Which things are must-haves? Which things can be flexible? Which things don't matter at all? This exercise will help you build a value-driven mental image, so be honest and think it over.
Now you know what matters to you. Next, to find out which schools align with your goals, try gathering information with these resources:
Take notes and ask targeted questions as needed.
Now you've looked at various schools. Next, categorize schools you're interested in based around your academic profile. You can reference this data with the College Scorecard website I mentioned above.
A balanced approach might include 2 colleges in each category. Apply to multiple schools to keep your options open. You can always adjust your list as you go.
Now you have a preliminary college list. Next, you can color it with data on the financials. The actual price you pay is usually much lower than the published tuition thanks to financial aid. Key steps include:
How documentation work moved through one structured defense team I worked on, plus the project management vocabulary you'll hear on most teams.
In the most structured team I've worked in, I had a folder for each CDRL (Contract Data Requirements List) that was a part of the contract (e.g., A001-XXX, A002-XXX, B001-XXX, B002-XXX, C001-XXX, C002-XXX, where XXX is the document type / name).
Inside each of these folders, I had two (2) folders: Working and SubmittedCopies. The Working folder contained the work-in-progress version of the document and any other stuff used to complete it; the SubmittedCopies folder contained the complete version/s of the document. When ready to submit, I emailed the person (whose role was to submit the documents) a list with the directory of the SubmittedCopies folder and the files they should submit.
I appended the submission date to the end of the filename in YYYYMMDD format. The CDRL number was at the beginning, followed by a submission number and revision letter. An example might be: C002-2A-Manual-20260131.docx. In this example...
Naming conventions vary by contract. Again, that was merely an example from my personal experience.
At first, I used TortoiseSVN to sync a local folder with a project folder on the company server. After editing a file stored locally on my computer, I "committed" my changes via right-click > TortoiseSVN > Commit, which caused the server's copy to be replaced with mine. Other people can use right-click > TortoiseSVN > Update to pull any committed changes into their local copy. If a person ever works on their local copy without updating first, it could lead to a conflict. They would need to revert all their work. This can be a troublesome workflow for that reason, but the commits do help to track changes with granularity. An alternative tool is SharePoint or Git.
For collaboration, I used a browser tool called SmartBear Collaborator. The interface in the browser displays the .docx or .pdf file but does not support direct edits; rather, it supports assigning individuals the role of reviewer. Then, the reviewers have a limited period of time to read the document and add "pins". The pins contain a message from the reviewer about an error or question and initially appear with red gumballs / bug icons. When all reviewers are done with this, the author then responds: either by answering the question, refuting the error, or correcting the error and re-uploading the document. After two versions of the document have been uploaded, the Collaborator view can display two side-by-side copies for the reviewers to compare and contrast. They confirm their requested changes were implemented by setting the pin as resolved, which changes the pin gumball to green.
Again, Collaborator supports Word natively for tracking changes, but the author must edit in Word or a code editing software, then re-upload the file to the Collaborator review.
This Collaborator process was repeated twice for each document submission: we had one review for the Quality Assurance (QA) team, then a second review for the Subject Matter Expert (SME) team. This way, several sets of eyes with different perspectives looked at the document before finally submitting it.
The customer returned their comments in the form of a Comment Resolution Matrix (CRM) spreadsheet. Thus, after the author responded to the CRM comments and made any necessary changes, the next set of QA and SME reviews would begin, this time with the CRM spreadsheet included as an attachment in both Collaborator reviews. Usually, only changes to the requested portions would be appropriate at this stage, since the rest of the content was tacitly accepted as correct by not being mentioned in the CRM. But there could be exceptions, according to common sense.
If the customer had any comments, the submission was "accepted conditionally" (if not outright "rejected") and required a resubmission.
A comment can either be "administrative" or "substantive". Administrative comments will refer to minor grammar and spelling mistakes, formatting mistakes, and errors on the title page or in the filename. Substantive comments will refer to inaccurate information, data errors, or anything deemed insufficient to meet the document's intent and purpose. If all the substantive comments were not resolved in a resubmission, the document would then need yet another resubmission or it would be rejected.
In practice, holding informal meetings with the customer prior to document submissions can prevent many CRM comments via the wonders of mutual understanding. The less particular the customer is, the fewer CRM comments they will return. It also helps when the customer's reviewer is a native English speaker well versed in the subject matter and the day-to-day particulars of the project.
Agile is a philosophy and set of values outlined in the so-called "2001 Agile Manifesto". It emphasizes iterative development, customer collaboration, and delivering (or just demonstrating) value on a set cadence. Agile itself is not the methodology. It's the umbrella term that includes frameworks such as Scrum and Kanban.
A sprint is a "time-boxed unit" of work used specifically within the Scrum framework (1–4 weeks, usually 2 weeks). During a sprint, the team works to complete a selected set of tasks that may or may not produce a "product increment" if that is applicable to the work at hand. If not, it still helps track progress on a macro level. Sprints create a predictable cadence of work from the perspective of leadership.
Agile is the name of a philosophy.
Scrum is a popular framework for applying Agile principles.
A sprint is the "time-boxed unit" within Scrum.
So, you can see that all three terms are related. I mostly engage with the sprint portion.
But not all Agile teams use sprints. Some use Kanban instead, which focuses on a continuous flow that is free from the "time-boxed unit". If you're in a sprint that uses a Kanban board, the concepts are being confused a bit.
Most teams use 2-week sprints. Once a sprint length is chosen, it should generally remain consistent. Holidays and various delays or what-have-you can push dates around though.
If a team fully integrates the Scrum framework, they can develop a sprint goal: a single objective that provides focus for the sprint and informs decisions throughout the duration of the sprint.
The "definition of done" is a standard that defines what "done" means for work items of all kinds (e.g., coding, documenting, testing, reviewing, deploying). Without a clear "definition of done", team members may go out of sync with each other and do too much (work that is out of scope) or not enough. That's why establishing a standard can help with consistency.
Teams constantly talk about dates moving, and some common phrases mean opposite things to different people. "The review was moved forward" could mean the review is now sooner, or now later. Researchers have asked people exactly this ("Next Wednesday's meeting has been moved forward two days. What day is it now?"), and the answers split roughly in half between Monday and Friday.
| Meaning | Phrases |
|---|---|
| Earlier | move up |
| Later | push back, push out |
| Ambiguous | move forward, push forward |
When you write about a schedule change, provide the full dates: "The review moved from Tuesday, March 10 to Friday, March 13." If you hear an ambiguous phrase in a meeting, consider asking for the new date to clarify things for everyone.
I can confirm these things exist. They were all a part of the structured team I mentioned above.
A standard sprint burndown chart shows the work remaining (in hours or story points) against the days of the sprint. An ideal line slopes down from the total on day one to zero on the last day, and a second line tracks the real progress. When the real line sits above the ideal line, the team is behind. Adding scope mid-sprint makes the real line jump up.
A version I've seen plots two lines instead: hours worked goes up and hours assigned goes down. The two lines are supposed to intersect in the middle of the sprint. If you add scope, it pushes back the location of the lines intersecting and leads to a higher percentage of overflow into the next sprint. This is a tool to diagnose problems with the work. Adding scope is something to be very careful about, especially for a "Firm Fixed Price" contract. So it helps to get the customer involved in the event of the team seriously needing to add scope.
I use Atlassian's Jira. Other tools include Azure DevOps, ClickUp, Linear, and physical Scrum boards.
There are a few important rules:
I have seen AI in professional work before. Obvious indicators include bullet points that start with emojis and the sentence framework, "it's not just X, it's Y" or "not with X, but with Y". Em dashes are a common pattern in AI text too, but they're not definitive proof. See Lesson 5 for when to use each.