0

Build a Read-Only Python Terminology Report for a Book Manuscript

A manuscript can be grammatically clear and still use its key terms inconsistently. One chapter calls an item a working note, another calls it a review note, and the reader cannot tell whether the distinction is intentional. A small local report can make those variations easier to inspect without pretending that a program understands the book. This guide builds a read-only Python utility for that narrow job. It is shared by the AIWriteBook project, was prepared with AI assistance, and is not an independent product review. All manuscript examples below are invented.

Define the editorial decision before automating it

Start with a terminology sheet that records what a phrase means in your manuscript. The preferred wording is an editorial choice, not a verdict returned by a regular expression. Two phrases may be genuine synonyms in one book and importantly different concepts in another. Before adding a variant to the configuration, write down why you want to review it and where the distinction is explained to readers.

The utility reports configured variants; it does not replace them. That separation matters because an old expression might appear appropriately inside a quotation, a historical example, or a discussion of an earlier approach. A global replacement would erase the context that tells you whether a change is needed. Treat the output as a short review queue and keep the author's judgment outside the script.

Keep the input contract small

Use a UTF-8 text or Markdown export and a JSON object mapping preferred terms to lists of variants. The program reads both files and prints JSON to standard output. It does not connect to a service, modify the manuscript, or write a report file unless you explicitly redirect the output. The encoding choice also accepts a UTF-8 byte-order mark, which can appear in files exported by some desktop tools.

For example, save this invented configuration as terminology.json. The mapping does not prove that these expressions mean the same thing; it merely records a decision that an author wants to inspect. Keep a real terminology sheet beside the configuration when the reasons behind a preference would otherwise be forgotten.

{"working note": ["review note", "working-note"]}

Save the following complete program as terms_audit.py. It uses only the Python standard library. The input object and variant lists are checked before scanning, so an empty pattern cannot accidentally produce a match at every position in every line.

import argparse
import json
import re
from pathlib import Path


def audit(text, terms):
    """Report configured variants outside backtick fences; never edit."""
    if not isinstance(terms, dict):
        raise ValueError("terms must be a JSON object")
    rules = []
    for preferred, variants in terms.items():
        if not isinstance(preferred, str) or not preferred.strip():
            raise ValueError("preferred terms must be nonempty strings")
        if not isinstance(variants, list):
            raise ValueError("variants must be lists")
        seen = {preferred.casefold()}
        for variant in variants:
            if not isinstance(variant, str) or not variant.strip():
                raise ValueError("variants must be nonempty strings")
            if variant.casefold() in seen:
                continue
            seen.add(variant.casefold())
            pattern = re.compile(r"(?<!\w)" + re.escape(variant) + r"(?!\w)", re.I)
            rules.append((preferred, variant, pattern))
    rows = []
    fenced = False
    for line_number, line in enumerate(text.splitlines(), start=1):
        if line.lstrip().startswith("```"):
            fenced = not fenced
            continue
        if fenced:
            continue
        for preferred, variant, pattern in rules:
            count = len(pattern.findall(line))
            if count:
                rows.append({"preferred": preferred, "variant": variant,
                             "line": line_number, "matches": count})
    return rows


def main():
    parser = argparse.ArgumentParser(description="Read-only terminology review")
    parser.add_argument("manuscript", type=Path)
    parser.add_argument("terms", type=Path)
    args = parser.parse_args()
    try:
        text = args.manuscript.read_text(encoding="utf-8-sig")
        terms = json.loads(args.terms.read_text(encoding="utf-8-sig"))
        rows = audit(text, terms)
    except (OSError, ValueError) as error:
        parser.error(str(error))
    print(json.dumps(rows, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()

Understand literal matching and boundaries

Each configured variant is escaped with re.escape. This makes punctuation part of the phrase rather than an instruction to the regular-expression engine. A configured expression such as C++ should not behave like a pattern written by a programmer. The configuration is a list of editorial labels, so interpreting its punctuation literally is the less surprising default.

The negative lookarounds reject a match when an adjacent character is a word character. With the example configuration, a review note can match while review notebook does not. Matching is case-insensitive, but it is not fuzzy matching, stemming, translation, or semantic comparison. Spaces, dashes and spelling differences must be represented explicitly. Remove accidental padding from configuration entries rather than expecting the script to normalize it.

The code also ignores a preferred term repeated as its own variant and deduplicates case-equivalent variants within the same entry. It does not deduplicate across different preferred terms. If two separate entries both contain the same variant, the output can contain two review items. That is a useful sign to inspect the terminology sheet rather than a reason to silently discard one interpretation.

Preserve line numbers without exposing whole passages

The report includes the preferred label, matched variant, source line number and number of matches on that line. It deliberately does not copy the surrounding manuscript passage. That keeps a shared review queue smaller and reduces accidental disclosure, although the term list itself can still reveal unpublished concepts. Store the report with the same care as the manuscript and avoid committing either file to an unrelated public repository.

Line numbers are one-based and refer to the exact exported text you scanned. They are not page numbers in a word processor or an EPUB. If you revise or re-export the manuscript, regenerate the report before following its locations. Keeping a report from an older export can make a correct result look misleading simply because the source moved.

Be explicit about the Markdown shortcut

The scanner skips lines between fences that begin with three backticks after optional leading whitespace. It still counts those lines when numbering subsequent prose. This is a deliberately small convenience for technical manuscripts, not a complete Markdown parser. It does not understand tilde fences, nested structures, inline code, HTML blocks, links or quoted material in the way a renderer would.

An unmatched opening backtick fence causes the remaining lines to be skipped. Check the export if a report is unexpectedly empty. Do not interpret zero matches as proof that a manuscript is consistent, and do not add increasingly complicated exceptions until the script becomes an undocumented parser. If your documents rely heavily on richer Markdown syntax, use an established parser and test its extracted prose separately.

Run a small example before a whole manuscript

Create a file called draft.md containing the invented line below, then run the command. Two occurrences on the same line produce one report row with a match count of two. The JSON output is intentionally plain so that it can be inspected directly or compared between revision passes.

Review note and REVIEW NOTE.
python terms_audit.py draft.md terminology.json

The expected row names working note as the preferred wording, review note as the variant, line one as the location and two as the match count. The utility exits normally when it finds review items; findings are not a software error. Missing files, invalid JSON or malformed configuration are reported through the command-line argument parser instead.

Test the behavior you are relying on

The complete source above was checked locally with six small standard-library unit tests. They cover case-insensitive counting and word boundaries, backtick-fence skipping with preserved line numbers, literal punctuation, duplicate variants and preferred-form exclusion, rejection of an empty variant, and leaving the supplied source text unchanged. Those checks support the limited behavior described here; they do not establish correctness for every language or document format.

Add examples from your own export process before relying on the report during a larger revision. Include an intentional quotation, a heading, an abbreviation and a phrase that must not match inside a longer word. When a test fails, decide whether the implementation is wrong or whether the stated input contract needs to change. Do not weaken an assertion merely to make the test suite green.

Fit the report into a drafting workflow

Project resource: best ai for writing a book. AIWriteBook supports fiction and nonfiction blueprints, outlines, editable chapter drafts and related story, plot and character tools. A free blueprint preview is available, while other capabilities may require a paid plan. This local checker is a separate illustrative utility, not an official integration or a claim that the application automatically enforces terminology.

AIWriteBook project illustration

The image is a project illustration from the official website, not evidence of a terminology-checking feature. Whether you draft manually or use AI assistance, review generated alternatives against the meanings you intend. Fluent wording can introduce a near-synonym that changes an explanation. A report can identify a configured surface form, but factual accuracy and the underlying distinction still require independent editorial work.

Finish with a bounded review pass

Scan a representative chapter, inspect the reported locations in the original export, and record decisions in your terminology sheet. Change the manuscript in its normal editor rather than building automatic replacements into this first version. Then export and scan again so that the report corresponds to the revised reading copy.

Keep the configuration small enough that you can explain every entry. The useful outcome is not a large count of warnings, nor an empty report treated as a certificate. It is a repeatable way to surface a specific class of editorial questions while preserving the source and making the program's limitations visible.


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí