AI Wiki中文/EN

Linguistic structure: one sentence, two attachments

语言结构基础

Inspect morphology, constituency, dependencies, meaning and context using two supplied trees and a complete structural checker.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Who had the drone?

Read this invented sentence: Maya photographed the scientist with the drone. Perhaps Maya used the drone to take the photograph. Perhaps the scientist was accompanied by it. The words alone do not force a choice. We can make the difference visible by attaching with the drone to the photography phrase or to the scientist phrase.

Linguistic structure gives us ways to represent such distinctions. Morphological features describe properties of word forms; syntax describes combinations and grammatical relations; semantics concerns interpretation; pragmatics examines language in its context of use. These are interacting questions, not a guarantee that a computer will resolve them in a fixed sequence.

The program supplies two analyses and checks their structure. It does not discover the parses, rank them, or claim they exhaust the sentence’s possible interpretations. This distinction matters: printing a correct-looking tree is not evidence that a parser can choose one from unseen text.

Two supplied dependency trees for the same seven words; the blue edge changes the head of drone, followed by finite Number constraints.
These are given analyses, not parser predictions. Both have six word edges; the head change raises maximum depth from 2 to 3. Feature intersections use only the miniature English lexicon.

Represent the difference before trying to resolve it

Morphology: a word form can leave a feature open

Our miniature English lexicon allows fish to be singular or plural. In the declared third-person present-tense setting, swims requires singular and swim requires plural. Combining the constraints selects a reading:

{Sing,Plur}∩{Plur}={Plur}.\{\mathrm{Sing},\mathrm{Plur}\}\cap\{\mathrm{Plur}\}=\{\mathrm{Plur}\}.

The program also supplies cat as singular and cats as plural. It is looking up a small feature lexicon, not discovering stems or segmenting suffixes. UD documents Number as a feature whose distribution and agreement behavior depend on the language; its values are not limited to our two-value teaching example. UD Number

More generally, each feature k maps to a finite allowed set. For two constraints A and B, our limited unification operation is:

U(A,B)[k]=A[k]∩B[k]U(A,B)[k]=A[k]\cap B[k]

when both specify k. An omitted feature imposes no new restriction. If any shared intersection is empty, the combination fails. This is finite-domain constraint intersection, not a full unification algorithm with variables, reentrancy or an occurs check.

Consequently fish swim yields Plur, fish swims yields Sing, and cat swim has no reading under this lexicon. That last statement is narrower than “the program proves every sentence of that shape ungrammatical.” I swim is outside its lexicon and would require a person distinction; rejecting it is an input-boundary decision, not an English grammar verdict.

Constituency: which words form a group?

A constituent representation groups words recursively. In the common abbreviations used here, S is a sentence, NP a noun phrase, VP a verb phrase and PP a prepositional phrase. A context-free grammar can state possible expansions, while a tree records a particular structure. Our code stores trees; it does not check them against a supplied grammar. SLP constituency chapter, definitions and bracket notation

The two supplied shapes are, schematically:

Verb attachment: S(NP Maya, VP(photographed, NP the scientist, PP with the drone))
Noun attachment: S(NP Maya, VP(photographed, NP(NP the scientist, PP with the drone)))

The actual program includes lexical labels and prints complete bracket strings. Both leaf sequences equal the same seven tokens:

index:   0       1          2      3       4     5     6
word:   Maya photographed  the  scientist  with  the  drone

Each node receives a half-open span [a,b), including a and excluding b:

length⁡([a,b))=b−a.\operatorname{length}([a,b))=b-a.

The PP occupies [4,7), of length three, in both trees. An NP spanning [2,7) exists only in the noun-attachment tree. The sentence spans [0,7) in both. Leaf equality therefore does not imply tree equality; the changed grouping is the information we wanted to retain.

Dependencies: which word is linked to which head?

A basic dependency representation uses labeled word-to-word relations. UD distinguishes its basic tree from enhanced dependencies that can form a more general graph. Our checker handles the basic-tree case only. UD syntax overview

Use zero-based word indices and reserve −1 for the artificial ROOT target. Each word i has one head h_i:

hi∈{−1,0,…,n−1},∑i=0n−11{hi=−1}=1.h_i\in\{-1,0,\ldots,n-1\},\qquad \sum_{i=0}^{n-1}\mathbf1\{h_i=-1\}=1.

There must also be no cycle. A head walk on a finite set either reaches −1 or repeats a node; excluding repetition and requiring one root makes every word connect to that root. Counting root entries alone is insufficient: another component could be cyclic.

In both analyses, word 1 (photographed) is the root, Maya has relation nsubj, and scientist has relation obj. The last head changes:

AnalysisHeads for indices 0 through 6Relation of droneMaximum word depth
Verb attachment[1,-1,3,1,6,6,1]obl of photographed2
Noun attachment[1,-1,3,1,6,6,3]nmod of scientist3

The two the tokens have relation det; with has relation case and attaches to drone. Both arrays contain six word-to-word edges plus the root entry. This follows the supplied UD-style content-word analysis; our indexing is not the one-based CoNLL-U file format. UD syntax, content words and function words

A dependency relation records an annotation decision. In this program obl does not automatically mean “instrument,” and nmod does not mean “owned by.” annotation_view returns subjects, objects, obliques and nominal modifiers. It deliberately does not rename these as agents, patients or owners.

Semantics: what would make the statement true?

One way to make an interpretation precise is to specify a model with a domain of entities and interpreted relations. Then a formula is evaluated relative to that model; a syntactically valid formula need not be true. The NLTK semantics chapter develops this distinction, including the role of variable assignments. NLTK, Truth in Model and Individual Variables

For our own deliberately simple thought experiment, let P be the relation “photographed” over pairs of people. A statement about Maya m and a scientist s is true exactly when their pair is included:

P(m,s)⟺(m,s)∈PM.P(m,s)\quad\Longleftrightarrow\quad(m,s)\in P^M.

A separate instrument relation or association relation would be required to express either drone interpretation. Neither is supplied by this pair alone or proven by the head arrays. We are not implementing a semantic parser or asserting that this small relation representation covers all meanings of the sentence.

Pragmatics: which situation and intended reference?

Even after choosing an attachment, the scientist and the drone may need context to identify their referents. In another invented utterance, Bring that drone here, interpreting that and here requires information about the utterance situation; its intended use also concerns what action the speaker is requesting. Pragmatics studies such roles of context and communicative intention. SEP Pragmatics, introduction

The boundary between semantics and pragmatics is debated. For an NLP implementation, the practical requirement is to state what context is available and what remains unresolved. A grammatical tree alone does not identify a physical drone or authorize an action.

Inspect supplied analyses with a complete program

Save the program as linguistic_structure.py and run python3 linguistic_structure.py. It uses only Python’s standard library; the recorded environment is Python 3.12.4. Its outputs are trees, spans, dependency edges and feature intersections, with no trained parameters or network access.

"""Original structural ambiguity and agreement examples, not a trained parser.

Two supplied analyses of one sentence. Validates constituency yields/spans and
basic dependency trees; an annotation view does not assert real-world meaning.
"""
import json
import re


def node(label,*children):
    return (label,tuple(children))


def tree_info(tree,expected_tokens=None):
    if not isinstance(tree,tuple):raise ValueError('A labeled tuple root is required')
    leaves=[];spans=[];parts=[]
    def visit(current,depth):
        if depth>64:raise ValueError('Teaching tree depth limit exceeded')
        if isinstance(current,str):
            if not current or any(c.isspace() or c in '()' for c in current):raise ValueError('Each leaf must be one unbracketed token')
            leaves.append(current);parts.append(current);return
        if not isinstance(current,tuple) or len(current)!=2:raise ValueError('Nodes are (label, children) tuples')
        label,children=current
        if not isinstance(label,str) or not re.fullmatch(r'[A-Z][A-Z0-9-]*',label) or not isinstance(children,tuple) or not children:raise ValueError('Nonempty labeled nodes required')
        begin=len(leaves);parts.append('('+label)
        for child in children:parts.append(' ');visit(child,depth+1)
        parts.append(')');spans.append([label,begin,len(leaves)])
    visit(tree,0)
    if expected_tokens is not None and tuple(leaves)!=tuple(expected_tokens):raise ValueError('Leaves do not match the supplied token sequence')
    return {'tokens':leaves,'spans_half_open':spans,'brackets':''.join(parts)}


def dependency_info(heads,relations):
    heads=list(heads);relations=list(relations);n=len(heads)
    if not 1<=n<=256 or len(relations)!=n:raise ValueError('Equal, bounded, nonempty annotation arrays required')
    if any(type(h) is not int or h < -1 or h>=n for h in heads):raise ValueError('Heads use zero-based word indices and -1 for ROOT')
    if any(not isinstance(r,str) or not r for r in relations):raise ValueError('A relation is required for every word')
    roots=[i for i,h in enumerate(heads) if h==-1]
    if len(roots)!=1:raise ValueError('A basic dependency tree needs exactly one root word')
    if any((h==-1)!=(r=='root') for h,r in zip(heads,relations)):raise ValueError('The root relation must match the ROOT edge')
    maximum_depth=0
    for start in range(n):
        seen=set();current=start
        while current!=-1:
            if current in seen:raise ValueError('Dependency cycle')
            seen.add(current);current=heads[current]
        maximum_depth=max(maximum_depth,len(seen)-1)
    return {'root':roots[0],'word_edges':n-1,'maximum_depth':maximum_depth,
            'edges':[{'head':h,'dependent':i,'relation':relations[i]} for i,h in enumerate(heads) if h!=-1]}


def unify(left,right):
    """Intersect shared finite feature domains; an omitted feature is unconstrained."""
    for mapping in [left,right]:
        if not isinstance(mapping,dict):raise ValueError('Feature dictionaries required')
        for key,values in mapping.items():
            if not isinstance(key,str) or not key or not isinstance(values,(set,frozenset)) or not values or any(not isinstance(v,str) or not v for v in values):raise ValueError('Nonempty sets of feature values required')
    result={}
    for key in sorted(left.keys()|right.keys()):
        values=left[key]&right[key] if key in left and key in right else left.get(key,right.get(key))
        if not values:return None
        result[key]=frozenset(values)
    return result


def number_readings(noun,verb):
    # A supplied third-person, present-tense English lexicon, not a universal rule.
    nouns={'fish':['Sing','Plur'],'cat':['Sing'],'cats':['Plur']}
    verbs={'swims':'Sing','swim':'Plur'}
    if noun not in nouns or verb not in verbs:raise ValueError('Word outside the miniature lexicon')
    results=[]
    for value in nouns[noun]:
        merged=unify({'Number':{value}},{'Number':{verbs[verb]}})
        if merged is not None:results.append({key:sorted(v) for key,v in merged.items()})
    return results


def examples():
    subject=node('NP',node('PN','Maya'));verb=node('V','photographed')
    scientist=node('NP',node('D','the'),node('N','scientist'))
    drone=node('NP',node('D','the'),node('N','drone'));phrase=node('PP',node('P','with'),drone)
    verb_attachment=node('S',subject,node('VP',verb,scientist,phrase))
    noun_attachment=node('S',subject,node('VP',verb,node('NP',scientist,phrase)))
    words=['Maya','photographed','the','scientist','with','the','drone']
    return words,{'verb_attachment':verb_attachment,'noun_attachment':noun_attachment}


def annotations(attachment):
    if attachment not in ['verb_attachment','noun_attachment']:raise ValueError('Unknown supplied reading')
    return [1,-1,3,1,6,6,1 if attachment=='verb_attachment' else 3],['nsubj','root','det','obj','case','det','obl' if attachment=='verb_attachment' else 'nmod']


def annotation_view(words,heads,relations):
    info=dependency_info(heads,relations)
    if len(words)!=len(heads) or any(not isinstance(w,str) or not w for w in words):raise ValueError('One surface token per annotation required')
    root=info['root']
    def dependents(relation):return [words[i] for i,h in enumerate(heads) if h==root and relations[i]==relation]
    return {'predicate_surface':words[root],'subjects':dependents('nsubj'),'objects':dependents('obj'),'obliques':dependents('obl'),
            'nominal_modifiers':[{'head':words[h],'modifier':words[i]} for i,h in enumerate(heads) if h!=-1 and relations[i]=='nmod']}


def demo():
    words,trees=examples();readings={}
    for name,tree in trees.items():
        heads,relations=annotations(name)
        readings[name]={'constituency':tree_info(tree,words),'dependency':dependency_info(heads,relations),
                        'heads':heads,'relations':relations,'annotation_view':annotation_view(words,heads,relations)}
    return {'sentence':' '.join(words),'tokens':len(words),'supplied_analyses':len(readings),'readings':readings,
            'agreement':{noun+' '+verb:number_readings(noun,verb) for noun,verb in [('fish','swim'),('fish','swims'),('cat','swim'),('cats','swim')]},
            'scope':'Two supplied analyses, not an exhaustive parse forest or a prediction. Basic dependency trees only; enhanced UD can be a graph. Surface subjects/objects are not automatically semantic agents/patients. Number lexicon is restricted to third-person present-tense English.'}


if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2))

tree_info checks tuple shape, nonempty node labels, one-token leaves and agreement with the supplied token sequence. It limits depth to 64. Its checks establish a well-formed representation, not grammaticality under a context-free grammar.

dependency_info checks 1–256 head entries, integer ranges, exactly one root, root-label agreement and absence of cycles. It does not verify the complete UD relation vocabulary or analyze enhanced edges. The worst-case head-walk cost is O(n²), since each of n starts may traverse a long chain; the temporary visited set uses O(n) space. This direct method is sufficient for the declared small input and is not advertised as an optimal dependency validator.

Tree traversal takes time proportional to the visited nodes plus the output text, and stores the leaf list, spans and bracket output. The unification routine intersects finite sets for shared features and copies constraints for unshared features, with sorted feature names for stable output. Its cost depends on those domain sizes, not on an exponential search over full sentence parses.

Fourteen tests cover both supplied readings, half-open spans, cycle/root failures, finite-domain agreement, invalid trees and word forms outside the miniature lexicon. A Chinese word can be a tree leaf, but that storage capability does not make the English agreement rules appropriate for Chinese. Draft checks separately run the program extracted from the paired MDX.

Representation is not successful analysis

A tokenizer’s boundary choices affect the units that receive spans and heads. If the representation changes, its old offsets and annotations need a defined conversion. Text normalization gives a concrete case where changing the string moves a span.

Different annotation schemes can encode related linguistic distinctions differently. Evaluate a parser against the chosen scheme and language, inspect annotation disagreements, and keep genuinely ambiguous alternatives where the task allows them. A short head array is not a universal theory of grammar; UD itself discusses the limits of dependency relations and cross-language parallelism. UD syntax overview

The program does not infer morphology from arbitrary forms, resolve scope or reference, learn a grammar, score candidates, or use visual context. Its two structures are teaching inputs. Algorithms that infer such structures belong in the later parsing topics; a full NLP pipeline also needs the task and evaluation contract.

Read the structure without inventing its meaning

  1. Basic understanding. In the verb-attachment analysis, drone has relation obl to photographed. Does the program thereby establish that Maya used the drone as a camera?

    Answer: No. It records that supplied syntactic relation. An instrument interpretation requires an additional semantic decision and relevant evidence; the code does not implement it.

  2. Hand calculation. With the listed seven tokens, how long is [4,7)? Which analysis contains an NP spanning [2,7)?

    Answer: Three tokens: with, the, drone. Only the noun-attachment analysis contains that five-token NP. Both analyses still have the same entire leaf sequence.

  3. Boundary case. Why does fish swims retain a reading while cat swim does not? Does the second result justify rejecting I swim as ungrammatical?

    Answer: Fish permits Sing or Plur, and swims selects Sing. Cat supplies Sing while this restricted swim entry requires Plur, giving an empty intersection. I is outside the lexicon and introduces a person distinction, so the program makes no grammar judgment about that sentence.

  4. Transfer. A system accepts head array [-1,2,1] because it contains exactly one root. What is missing, and would fixing that check resolve the meaning of that drone?

    Answer: Words 1 and 2 form a cycle; head walks must also be checked. Rejecting that malformed tree repairs a structural invariant. Resolving a demonstrative’s reference still needs a separate context-sensitive interpretation step.

Use each source for the layer it actually describes

The SLP chapter supplies constituency and grammar notation. Pinned UD documentation supplies dependency conventions and Number features, with language-specific limits. The pinned NLTK chapter supplies the distinction between formulas and model-relative meaning. The archived SEP entry supplies a scholarly overview of context and intention, not an executable reference-resolution algorithm.

Our sentence, tree pair, head arrays, finite lexicon, relation thought experiment and exercises are original. The scope remains inspectable: two supplied analyses, seven tokens, six word edges and a small agreement table. No parser accuracy, comprehensive linguistic theory or human understanding score is inferred from them.

Make a prediction, then check

Both trees have identical leaves. What follows?

Choose one answer

Learning objectives

  • Separate form features, syntax, interpretation and context.
  • Compare two structures with the same word sequence.
  • Validate spans and a basic dependency tree without claiming grammaticality.
  • Use finite feature constraints while preserving language-specific limits.

Prerequisites & connections

Explore related knowledge →

References

  1. Speech and Language Processing, constituency chapter, August 19 2026 draft
    Daniel Jurafsky; James H. Martin · 2026
  2. Universal Dependencies syntax overview, pinned revision
    Universal Dependencies contributors · 2026
  3. Universal Dependencies Number feature, pinned revision
    Universal Dependencies contributors · 2026
  4. Natural Language Processing with Python, chapter 10, pinned source
    Steven Bird; Ewan Klein; Edward Loper
  5. Pragmatics, Stanford Encyclopedia of Philosophy, Summer 2026 archive
    Kepa Korta; John Perry · 2024

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-08 · Codex single-AI-author technical check: scoped constituency, pinned UD features/dependencies, pinned model semantics and archived pragmatics; five paired equations, supplied trees/spans/heads, finite Number intersections, separation of annotation and meaning, four explained exercises and computed SVGs. Not a trained parser, exhaustive grammar, human peer review or full UD conformance. Production browser acceptance recorded separately.

  • Compared both manuscripts: morphology versus finite lexicon lookup, missing versus empty feature domains, constituent grouping and half-open spans, basic head-tree root/cycle conditions, model-relative predicates and contextual reference. Five paired equations and four explained exercises.
  • Fourteen structural/feature tests are embedded in the production suite plus six publication checks. Two supplied seven-token analyses, six word edges each, actual depths2/3, larger NP only in noun attachment, invalid heads/cycles, feature conflicts and unsupported language scope.
  • No CFG rule validation, trained parsing, universal English agreement or automatic instrument/ownership interpretation. The semantics relation is an original thought experiment; archived pragmatics is a scholarly overview, not an executed reference resolver.
  • Four original SVGs bind actual output and raw data. Final isolated bilingual, three-width/four-font validation passed and desktop/mobile screenshots were inspected. Full article acceptance is recorded separately. Single-AI-author technical check, not independent human review; no upstream code copied or executed.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.