概要
cntextは社会科学のテキスト分析向けPythonライブラリで、中国語テキストから態度や心理状態などの構成概念を測定するため、単語頻度、感情分析、単語埋め込み、意味投影を提供します。
AI・機械学習計測したスター増加
- 24時間
- 0
- 7日間
- 0
- 15日間
- 0
- 1か月
- +3
期間ごとの純増数です。期間は重複しており、日別の値ではありません。未計測の値は空欄です。スター数は注目度の指標であり、品質の保証ではありません。
README.md
オリジナルTable of Contents
- cntext: Text Analysis for Computational Social Science
- Word Embedding Projection Approach (WEPA)
- Installation
- Minimal Runnable WEPA Example
- WEPA Documentation and Reproducibility Files
- Quick Start
- Module Overview
- 1. IO Module
- 2. Stats Module
- 3. Plot Module
- 4. Model Module
- 5. Mind Module
- 5.1
semantic_centroid(wv, words) - 5.2
generate_concept_axis(wv, poswords, negwords) - 5.3
anchor_pole_diagnostics(wv, poswords, negwords, return_frame) - 5.4
semantic_axis_stability(reference_wv, comparison_wvs, poswords, negwords) - 5.5
wepa(wv, text, poswords, negwords, lang, cosine) - 5.6
project_text(wv, text, axis, lang, cosine) - 5.7
sematic_projection() - 5.8
project_word() - 5.9
sematic_distance() - 5.10
divergent_association_task() - 5.11
discursive_diversity_score() - 5.12
procrustes_align()
- 5.1
- 6. LLM Module
- Anchor Dictionary Format for WEPA
- Responsible Use
- Documentation
- Citation
- License
cntext: Text Analysis for Computational Social Science
cntext is a Python package for computational social science researchers who work with text data. It supports file reading, dictionary-based analysis, word frequency statistics, readability, similarity, word embeddings, semantic projection, plotting, and LLM-assisted structured text analysis.
中文说明见:README_CN.md。
What cntext helps researchers do:
- Build structured research datasets from unstructured files
- combine many
txt,pdf,docx,csv,xlsx, orxlsfiles into analysis-ready tables withct.read_files(); - extract Management Discussion and Analysis (MD&A) sections from Chinese annual reports with
ct.extract_mda(); - clean Chinese or English text before dictionary analysis, embedding training, or LLM-assisted coding.
- combine many
- Run traditional transparent text analysis
- compute word frequencies and lexical concentration with
ct.word_count()andct.word_hhi(); - score sentiment or semantic categories with built-in or custom dictionaries;
- search target words in context and inspect concordance windows.
- compute word frequencies and lexical concentration with
- Train and use domain-specific embeddings
- train
Word2Vec,GloVe, orFastTextmodels from local corpora; - evaluate embeddings with similarity and analogy tasks;
- expand seed dictionaries with embedding neighbors or co-occurrence methods.
- train
- Measure semantic constructs with theory-driven projection
- define semantic concept axes, such as commitment vs. avoidance or innovation vs. conservatism;
- project words or texts onto these axes;
- diagnose anchor-pole separation and semantic-axis stability for WEPA-style measurement.
- Combine rule-based workflows with LLM-assisted structured analysis
- define task prompts and output schemas;
- use LLMs for classification, extraction, summarization, and theory-guided annotation.
This repository now foregrounds reproducible support for the Word Embedding Projection Approach (WEPA) introduced in the manuscript:
Reviewer entry point: open WEPA-DEMO/01-WEPA-Intro.md for the paper-oriented WEPA demo, then follow the three reproducible workflow files in WEPA-DEMO/.
Word Embedding Projection Approach (WEPA)
WEPA is a theory-driven semantic projection workflow for measuring construct-related linguistic salience in user-generated text. It represents a psychological or social construct as a semantic axis in a word-embedding space. The axis is defined by theory-based positive pole and negative pole anchor words. A text is then projected onto that axis to obtain a text-based indicator.
In cntext, the shortest WEPA scoring path is one line:
import cntext as ct
wv = ct.load_w2v('/path/Embeddings.bin')
score = ct.wepa(
wv=wv,
text="I will persist and focus on this goal",
poswords=["commit", "persist", "focus"],
negwords=["quit", "avoid", "delay"],
lang="english",
)
This one-line call is equivalent to the expanded workflow:
import cntext as ct
wv = ct.load_w2v('outputs/corpus-Word2Vec.200.15.bin')
axis = ct.generate_concept_axis(
wv=wv,
poswords=["commit", "persist", "focus"],
negwords=["quit", "avoid", "delay"],
)
score = ct.project_text(
wv=wv,
text="I will persist and focus on this goal",
axis=axis,
lang="english",
)
WEPA scores should be interpreted as indicators of construct-related linguistic salience in text. They should not be interpreted as direct observations of latent psychological states, clinical diagnoses, causal effects, or proof of strict measurement invariance. Anchor-word dictionaries are context-specific measurement resources. They should be developed from theory, reviewed by domain experts, and validated empirically before being used in new platforms, languages, or cultural contexts.
Installation
Install the latest released package:
pip install cntext --upgrade
Recommended Python versions: Python 3.9 to 3.12.
For local development from this repository:
pip install -e .
Minimal Runnable WEPA Example
The repository includes a small example that does not require external datasets, large embedding files, or internet access:
python examples/wepa_minimal_example.py
If your system uses python3:
python3 examples/wepa_minimal_example.py
The example creates a tiny in-memory embedding object, defines positive and negative anchor words for a goal-commitment construct, constructs a semantic axis, scores several toy texts, and prints a small table.
WEPA Documentation and Reproducibility Files
- Paper demo entry point:
WEPA-DEMO/01-WEPA-Intro.md - Build corpus demo:
WEPA-DEMO/2. Build-Corpus.md - Train embeddings demo:
WEPA-DEMO/3. Train-Embeddings.md - Semantic-axis and scoring demo:
WEPA-DEMO/4. Semantic-Axis-And-Scoring.md - WEPA guide:
docs/wepa.md - Paper reproducibility guide:
docs/paper_reproducibility.md - Minimal example script:
examples/wepa_minimal_example.py - Anchor dictionary format:
examples/wepa_anchor_dictionary_format.md - Lightweight WEPA tests:
tests/test_wepa.py
Run the WEPA tests:
python -m pytest tests/test_wepa.py
or:
python3 -m pytest tests/test_wepa.py
The public repository supports reproducibility of the WEPA scoring workflow. The raw platform data used in the manuscript are not redistributed because they contain user-generated content and must be protected for privacy reasons. Full reproduction of the empirical tables requires access to the original de-identified research dataset and the corresponding research-use permissions.
Quick Start
import cntext as ct
print("cntext version:", ct.__version__)
ct.hello()
Common workflow:
import cntext as ct
text = "The product is useful, reliable, and easy to use."
dictionary_data = ct.read_yaml_dict("en_common_NRC.yaml")
sentiment_dictionary = dictionary_data["Dictionary"]
result = ct.sentiment(
text=text,
diction=sentiment_dictionary,
lang="english",
)
print(result)
Module Overview
cntext contains six main areas.
| Area | Main functions | Description |
|---|---|---|
io |
get_cntext_path, get_dict_list, read_yaml_dict, read_pdf, read_docx, read_file, read_files, get_files, extract_mda, traditional2simple, fix_text, fix_contractions, clean_text |
Read files, load dictionaries, clean text, and prepare research datasets. |
stats |
word_count, readability, sentiment, sentiment_by_valence, word_in_context, epu, fepu, semantic_brand_score, cosine_sim, jaccard_sim, minedit_sim, word_hhi |
Compute word counts, readability, dictionary scores, similarity measures, and domain indicators. |
plot |
matplotlib_chinese, lexical_dispersion_plot1, lexical_dispersion_plot2 |
Create lexical dispersion plots and configure Matplotlib for CJK text rendering. |
model |
Word2Vec, GloVe, FastText, SoPmi, load_w2v, glove2word2vec, expand_dictionary, evaluate_similarity, evaluate_analogy |
Train, load, evaluate, and use embedding models and dictionary expansion tools. |
mind |
generate_concept_axis, anchor_pole_diagnostics, semantic_axis_stability, project_text, wepa, sematic_projection, project_word, semantic_centroid, sematic_distance, procrustes_align, divergent_association_task, discursive_diversity_score |
Measure semantic projection, construct-related linguistic salience, anchor validity, temporal stability, semantic distance, embedding alignment, and related indicators. |
llm |
llm, analysis_by_llm, text_analysis_by_llm |
Use LLMs for structured text analysis tasks. |
Typical research workflows:
- Document-to-data workflow: use
get_files()to locate documents,read_files()to build a DataFrame,clean_text()to normalize text, andword_count()orsentiment()to produce document-level variables. - Annual-report workflow: use
read_pdf()to extract report text,extract_mda()to isolate MD&A content, andfepu()or custom dictionaries to construct firm-level text indicators. - Dictionary workflow: inspect built-in dictionaries with
get_dict_list(), load a YAML dictionary withread_yaml_dict(), adapt it to the target domain, then usesentiment()orsentiment_by_valence(). - Embedding workflow: prepare a domain corpus, train
Word2Vec()orGloVe(), evaluate model quality, then useexpand_dictionary(),generate_concept_axis(),project_text(), orwepa(). - WEPA measurement workflow: define construct poles from theory, validate anchor words with
anchor_pole_diagnostics(), construct an axis withgenerate_concept_axis(), score texts withwepa(), and check longitudinal comparability withsemantic_axis_stability().
1. IO Module
The IO module helps researchers load files, inspect built-in dictionaries, clean text, and prepare corpora for analysis.
1.1 get_dict_list()
List the built-in YAML dictionaries.
import cntext as ct
ct.get_dict_list()
Typical built-in dictionary files include:
| Dictionary file | Language | Typical use |
|---|---|---|
zh_common_HowNet.yaml |
Chinese | General positive and negative sentiment words from HowNet-style resources. |
zh_common_DUTIR.yaml |
Chinese | Fine-grained emotion categories, including joy, anger, sadness, fear, surprise, good, and disgust. |
zh_common_NTUSD.yaml |
Chinese | Traditional Chinese sentiment dictionary. |
zh_common_LoughranMcDonald.yaml |
Chinese | Finance-oriented positive and negative words adapted from Loughran-McDonald style dictionaries. |
zh_common_EPU.yaml |
Chinese | Economic Policy Uncertainty terms for news-style EPU measurement. |
zh_common_FEPU.yaml |
Chinese | Firm-level economic policy uncertainty perception terms for corporate text. |
zh_valence_ChineseEmoBank.yaml |
Chinese | Valence and arousal resources based on Chinese affective norms. |
zh_valence_SixSemanticDimensionDatabase.yaml |
Chinese | Six semantic dimensions: vision, socialness, emotion, time, space, and motor. |
en_common_NRC.yaml |
English | NRC emotion and sentiment categories. |
en_common_LoughranMcDonald.yaml |
English | Financial sentiment categories, including negative, positive, uncertainty, litigious, modal, and constraining terms. |
en_common_LSD2015.yaml |
English | Lexicoder Sentiment Dictionary. |
en_common_SentiWS.yaml |
German | German positive and negative sentiment words. |
en_valence_Concreteness.yaml |
English | Word-level concreteness ratings. |
enzh_common_StopWords.yaml |
Chinese and English | Stop-word lists for preprocessing. |
enzh_common_AdvConj.yaml |
Chinese and English | Adverbs and conjunctions useful for rhetorical or contextual analysis. |
1.2 Built-in YAML Dictionaries
cntext dictionaries are stored as YAML files. A dictionary usually contains metadata and a Dictionary field. For example:
Name: Example Dictionary
Desc: Short description of the dictionary.
Refer: Reference information.
Category:
- positive
- negative
Dictionary:
positive:
- good
- reliable
negative:
- bad
- risky
Built-in dictionaries cover general sentiment, finance, uncertainty, stop words, rhetorical categories, concreteness, and other lexical resources. They are useful starting points, but researchers should check whether a dictionary is appropriate for their research domain.
1.3 read_yaml_dict()
Load a built-in or custom YAML dictionary.
import cntext as ct
data = ct.read_yaml_dict("en_common_NRC.yaml")
dictionary = data["Dictionary"]
Function signature:
ct.read_yaml_dict(yfile, is_builtin=True)
Parameters:
yfile: YAML dictionary filename or path.is_builtin: ifTrue, read from cntext built-in dictionaries; ifFalse, read from a user-provided file path.
Returns:
- A Python dictionary containing dictionary metadata and lexical categories.
The returned object commonly includes:
Name: dictionary name.Desc: concept definition or short description.Refer: source or bibliographic reference.Category: dictionary categories.Dictionary: a Python dictionary that maps category names to word lists or weighted entries.
Custom YAML dictionaries should keep this structure when possible. This makes the dictionary easier to inspect, cite, and reuse in later research.
1.4 detect_encoding()
Detect the encoding of a text file.
encoding = ct.detect_encoding("data/example.txt")
print(encoding)
Function signature:
ct.detect_encoding(file, num_lines=100)
1.5 get_files(fformat)
Return files matching a path pattern.
files = ct.get_files("data/*.txt")
This is useful for building file-level datasets from a folder of text, PDF, Word, or CSV files.
Examples of path patterns:
| Pattern | Meaning |
|---|---|
"*.txt" |
All text files in the current working directory. |
"data/*.txt" |
All text files in the data folder. |
"reports/*.pdf" |
All PDF files in the reports folder. |
"data/**/*.txt" |
Text files in nested folders when the underlying glob behavior supports recursive matching. |
1.6 read_pdf()
Read text from a PDF file.
text = ct.read_pdf("data/report.pdf")
Function signature:
ct.read_pdf(file)
1.7 read_docx()
Read text from a Word document.
text = ct.read_docx("data/report.docx")
Function signature:
ct.read_docx(file)
1.8 read_file()
Read a single file.
text = ct.read_file("data/example.txt", encoding="utf-8")
Function signature:
ct.read_file(file, encoding="utf-8")
Supported file types include plain text, PDF, Word, Excel, and CSV files. For tabular inputs, the function returns the parsed content in a DataFrame-compatible form. For text-like inputs, it returns extracted textual content.
1.9 read_files()
Read multiple files matching a pattern and return a DataFrame.
df = ct.read_files("data/*.txt", encoding="utf-8")
The returned DataFrame can be used as an input table for later text analysis.
Typical output columns:
file: source filename or path.doc: extracted document text.
This function is useful when each file is one research observation, such as one annual report, one news article, one interview transcript, or one user-generated document.
1.10 extract_mda()
Extract Management Discussion and Analysis text from annual-report content when the report structure supports extraction.
mda_text = ct.extract_mda(report_text)
Function signature:
ct.extract_mda(text, kws_pattern="")
Notes:
- This function is designed for financial-report workflows.
- Extraction quality depends on report formatting and section headings.
- Researchers should inspect extraction results before using them in empirical analysis.
The built-in section-title pattern covers common Chinese headings such as:
董事会报告|董事会报告与管理讨论|企业运营与管理评述|经营总结与分析|管理层评估与未来展望|董事局报告|管理层讨论与分析|经营情况讨论与分析|经营业绩分析|业务回顾与展望|公司经营分析|管理层评论与分析|执行摘要与业务回顾|业务运营分析
If a report uses unusual section headings, provide a custom kws_pattern and inspect the extracted text manually.
1.11 traditional2simple()
Convert Traditional Chinese text to Simplified Chinese text, or the reverse when a different mode is supplied.
converted = ct.traditional2simple(text, mode="t2s")
Function signature:
ct.traditional2simple(text, mode="t2s")
1.12 fix_text()
Repair garbled or inconsistent text encoding with ftfy.
cleaned = ct.fix_text(raw_text)
1.13 fix_contractions()
Expand English contractions.
ct.fix_contractions("you're right")
Output:
you are right
1.14 clean_text()
Clean text for Chinese or English preprocessing.
cleaned = ct.clean_text(text, lang="english")
Function signature:
ct.clean_text(text, lang="chinese")
Supported values:
lang="chinese"lang="english"
2. Stats Module
The Stats module provides traditional text statistics, dictionary scoring, contextual word search, uncertainty indicators, brand salience, similarity measures, and lexical concentration.
2.1 word_count()
Count words or tokens in a text.
result = ct.word_count("This is a short example text.", lang="english")
Function signature:
ct.word_count(text, lang="chinese")
2.2 readability()
Compute readability indicators.
result = ct.readability(text, lang="english")
Function signature:
ct.readability(text, lang="chinese", syllables=3)
Notes:
- English readability uses sentence and word information.
- Chinese readability depends on the package's tokenization and length assumptions.
- Readability indicators should be interpreted as descriptive features, not as direct quality scores.
2.3 sentiment(text, diction, lang)
Compute dictionary-based sentiment or category counts with equal word weights.
dictionary = {
"positive": ["good", "reliable", "useful"],
"negative": ["bad", "risky", "weak"],
}
result = ct.sentiment(
text="The product is reliable and useful.",
diction=dictionary,
lang="english",
)
Function signature:
ct.sentiment(text, diction, lang="chinese", return_series=False)
Returns:
- Category counts such as
positive_numandnegative_num. - Text-level counts such as
word_num,sentence_num, andstopword_num.
Dictionary format:
dictionary = {
"positive": ["good", "reliable", "useful"],
"negative": ["bad", "risky", "weak"],
}
Each key is treated as a category. cntext counts how many category words appear in the tokenized text. This makes the function suitable for transparent dictionary-based variables, but the result depends on dictionary coverage, tokenization quality, and domain fit.
2.4 sentiment_by_valence()
Compute dictionary-based scores when dictionary entries carry numeric values.
valence_dictionary = {
"word": ["good", "bad"],
"valence": [1.0, -1.0],
}
result = ct.sentiment_by_valence(
text="good good bad",
diction=valence_dictionary,
lang="english",
)
Function signature:
ct.sentiment_by_valence(text, diction, lang="chinese", mean=False, return_series=False)
Weighted dictionary format:
weighted_dictionary = {
"word": ["good", "bad", "uncertain"],
"valence": [1.0, -1.0, -0.3],
}
Use mean=True when the score should be normalized by matched word count. Use mean=False when the total weighted signal is substantively meaningful, for example when document length is part of the construct.
2.5 word_in_context()
Find keywords and return their surrounding context.
contexts = ct.word_in_context(
text="The team will commit to the goal and persist.",
keywords=["commit", "persist"],
window=3,
lang="english",
)
Function signature:
ct.word_in_context(text, keywords, window=3, lang="chinese")
Returns:
- A table-like object containing matched keywords and their surrounding context.
- Context windows are useful for dictionary validation because they reveal whether a term is used with the expected meaning in the target corpus.
2.6 epu()
Compute or load an Economic Policy Uncertainty indicator using the package workflow.
df = ct.epu()
Researchers should inspect the underlying corpus, dictionary choices, and time aggregation before using EPU results in empirical models.
2.7 fepu()
Compute firm-level economic policy uncertainty perception from text.
result = ct.fepu(text)
Function signature:
ct.fepu(text, ep_pattern="", u_pattern="")
Parameters:
text: corporate text, often MD&A or annual-report text.ep_pattern: optional economic-policy term pattern.u_pattern: optional uncertainty term pattern.
Use custom patterns when the research domain requires different economic-policy or uncertainty vocabularies.
2.8 semantic_brand_score()
Compute Semantic Brand Score indicators for brands, organizations, individuals, or keywords.
result = ct.semantic_brand_score(
text=text,
brands=["brand_a", "brand_b"],
lang="english",
)
Function signature:
ct.semantic_brand_score(text, brands, lang="chinese", co_range=7, link_filter=2)
The Semantic Brand Score combines prevalence, diversity, and connectivity. Researchers should choose the co-occurrence range and filtering parameters according to the corpus and research question.
Returned indicators typically include:
prevalence: how often a brand or target keyword appears.diversity: how diverse the words connected to the target are.connectivity: how central the target is in the co-occurrence network.SBS: the combined Semantic Brand Score.
2.9 Text Similarity
cntext includes several text similarity measures.
text1 = "The company invests in innovation."
text2 = "The firm supports innovative research."
ct.cosine_sim(text1, text2, lang="english")
ct.jaccard_sim(text1, text2, lang="english")
ct.minedit_sim(text1, text2, lang="english")
ct.simple_sim(text1, text2, lang="english")
Functions:
ct.cosine_sim(text1, text2, lang="chinese")
ct.jaccard_sim(text1, text2, lang="chinese")
ct.minedit_sim(text1, text2, lang="chinese")
ct.simple_sim(text1, text2, lang="chinese")
2.10 word_hhi()
Compute the Herfindahl-Hirschman Index of word concentration in a text.
hhi = ct.word_hhi(text)
This can be used as a descriptive indicator of lexical concentration or repetition.
Interpretation:
- Higher HHI indicates that a smaller number of words dominate the text.
- Lower HHI indicates more even word usage.
- HHI is descriptive; it should be interpreted with text length and preprocessing choices in mind.
3. Plot Module
The Plot module provides helper functions for lexical dispersion visualization and CJK font support.
3.1 matplotlib_chinese()
Configure Matplotlib to display CJK text.
ct.matplotlib_chinese()
3.2 lexical_dispersion_plot1()
Plot where target words appear within a single text.
targets = {
"positive": ["good", "strong", "reliable"],
"negative": ["bad", "weak", "risky"],
}
ct.lexical_dispersion_plot1(
text=text,
targets_dict=targets,
lang="english",
title="Lexical dispersion",
)
Function signature:
ct.lexical_dispersion_plot1(text, targets_dict, lang, title, figsize)
3.3 lexical_dispersion_plot2()
Plot target-word positions across multiple texts.
texts = {
"document_a": "The team will commit and persist.",
"document_b": "The team may delay or avoid the goal.",
}
ct.lexical_dispersion_plot2(
texts_dict=texts,
targets=["commit", "persist", "delay", "avoid"],
lang="english",
title="Cross-document lexical dispersion",
)
Function signature:
ct.lexical_dispersion_plot2(texts_dict, targets, lang, title, figsize)
4. Model Module
The Model module supports corpus preprocessing, embedding training, model loading, model evaluation, and dictionary expansion.
4.1 Word2Vec()
Train a Word2Vec model from a local corpus file.
wv = ct.Word2Vec(
corpus_file="examples/data/w2v_corpus.txt",
lang="english",
vector_size=100,
window_size=6,
min_count=5,
max_iter=5,
)
Function signature:
ct.Word2Vec(
corpus_file,
lang="chinese",
dict_file=None,
stopwords_file=None,
vector_size=100,
window_size=6,
min_count=5,
max_iter=5,
chunksize=10000,
only_binary=True,
**kwargs,
)
Returns:
- A Gensim
KeyedVectorsmodel.
Notes:
- The corpus file should be plain text.
- Use a domain-relevant corpus when the model will be used for WEPA or other construct measurement.
- Store model parameters and preprocessing choices for reproducibility.
Important parameters:
corpus_file: path to a plain-text corpus file.lang: preprocessing language; common values are"chinese"and"english".dict_file: optional user dictionary for Chinese segmentation.stopwords_file: optional stop-word file.vector_size: embedding dimension.window_size: context window size.min_count: minimum word frequency kept in the vocabulary.max_iter: number of training iterations.only_binary: whether to save only the binary model file.
Practical guidance:
- Increase
vector_sizewhen the corpus is large enough and the measurement task requires richer semantic distinctions. - Increase
window_sizewhen broader topical context matters. - Use a larger
min_countfor noisy corpora, but check that anchor words remain in vocabulary. - For WEPA, always report corpus period, preprocessing,
vector_size,window_size,min_count, andmax_iter.
4.2 GloVe()
Train a GloVe model from a local corpus file.
wv = ct.GloVe(
corpus_file="examples/data/w2v_corpus.txt",
lang="english",
vector_size=100,
window_size=15,
min_count=5,
max_iter=15,
)
Function signature:
ct.GloVe(
corpus_file,
lang="chinese",
dict_file=None,
stopwords_file=None,
vector_size=100,
window_size=15,
min_count=5,
max_memory=4.0,
max_iter=15,
x_max=10,
chunksize=100000,
only_binary=True,
)
Important parameters:
max_memory: memory limit used by the underlying GloVe workflow.x_max: weighting cutoff parameter in GloVe.max_iter: number of training iterations.window_size: co-occurrence window size.
GloVe is often useful when researchers want stable co-occurrence-based semantic representations. As with Word2Vec, the model should be trained on text that matches the research domain.
4.3 evaluate_similarity()
Evaluate an embedding model on word similarity data.
ct.evaluate_similarity(wv)
Function signature:
ct.evaluate_similarity(wv, file=None)
If file is None, cntext uses a built-in evaluation file. You can also provide a custom similarity evaluation file.
Custom similarity files should contain word pairs and human similarity scores. Domain-specific evaluation files are often more informative than general-purpose benchmarks when the embedding model is trained on specialized corpora such as finance, fitness, medicine, or policy text.
4.4 evaluate_analogy()
Evaluate an embedding model on analogy data.
ct.evaluate_analogy(wv)
Function signature:
ct.evaluate_analogy(wv, file=None)
If file is None, cntext uses a built-in analogy evaluation file. You can also provide a custom analogy evaluation file.
Analogy evaluation is a rough diagnostic. A model can perform poorly on generic analogy tasks but still be useful for domain-specific semantic projection if it represents the target vocabulary and constructs well.
4.5 SoPmi()
Expand seed dictionaries with a co-occurrence based semantic orientation method.
result = ct.SoPmi(
corpus_file="examples/data/sopmi_corpus.txt",
seed_file="examples/data/sopmi_seed_words.txt",
lang="english",
)
Function signature:
ct.SoPmi(corpus_file, seed_file, lang="chinese")
Seed files usually contain category labels and seed words. The method is useful for discovering candidate words that co-occur with seed categories, but expanded lists should be manually reviewed before being treated as validated dictionaries.
4.6 load_w2v()
Load a Word2Vec or GloVe model file that is compatible with cntext.
wv = ct.load_w2v("path/to/model.bin")
Function signature:
ct.load_w2v(wv_path)
Common use cases:
- load a model trained by
ct.Word2Vec()orct.GloVe(); - load a compatible binary word2vec model;
- reuse a previously trained domain model for projection or dictionary expansion.
After loading, inspect vocabulary coverage for your task:
anchors = ["commit", "persist", "focus", "quit", "avoid", "delay"]
coverage = [word for word in anchors if word in wv]
print(coverage)
4.7 glove2word2vec()
Convert a GloVe text model file into Word2Vec text format.
ct.glove2word2vec(
glove_file="path/to/glove.txt",
word2vec_file="path/to/word2vec.txt",
)
Function signature:
ct.glove2word2vec(glove_file, word2vec_file)
4.8 Notes on Embedding Models
For WEPA, embedding choice is part of the measurement design. Researchers should report:
- corpus source,
- platform and time period,
- tokenization and preprocessing,
- embedding algorithm,
- vector size,
- window size,
- minimum count threshold,
- training iterations,
- vocabulary coverage for anchor words and scored texts.
4.9 expand_dictionary()
Expand a seed dictionary with embedding neighbors.
seed_dictionary = {
"quality": ["reliable", "durable"],
"innovation": ["novel", "creative"],
}
expanded = ct.expand_dictionary(
wv=wv,
seeddict=seed_dictionary,
topn=100,
)
Function signature:
ct.expand_dictionary(wv, seeddict, topn=100)
Dictionary expansion can help identify candidate words, but the expanded terms should be reviewed before use as measurement dictionaries.
Suggested dictionary-expansion workflow:
- Start from a small, theory-grounded seed dictionary.
- Use
expand_dictionary()to collect nearest neighbors in a domain embedding model. - Remove ambiguous, overly general, or domain-inappropriate candidates.
- Check candidate words in context with
word_in_context(). - Document inclusion and exclusion decisions.
5. Mind Module
The Mind module provides embedding-based tools for semantic projection, WEPA scoring, anchor validation, temporal comparability checks, semantic distance, and related cognitive or cultural text indicators.
5.1 semantic_centroid(wv, words)
Purpose:
Compute the normalized semantic centroid of a word list. This is useful when several words jointly represent one concept, topic, or semantic prototype.
Parameters:
wv: A word embedding model or compatibleKeyedVectorsobject.words: A list of words. Words missing fromwvare skipped.
Returns:
- A normalized NumPy vector. If none of the words are in the vocabulary, the function returns a zero vector.
Example:
centroid = ct.semantic_centroid(
wv=wv,
words=["commit", "persist", "focus"],
)
5.2 generate_concept_axis(wv, poswords, negwords)
Purpose:
Construct a normalized bipolar semantic axis from positive and negative anchor words. The axis points from the negative pole toward the positive pole and is the core geometric object used by WEPA.
Parameters:
wv: A word embedding model or compatibleKeyedVectorsobject.poswords: Non-empty list of positive-pole anchor words.negwords: Non-empty list of negative-pole anchor words.
Returns:
- A unit-length NumPy vector representing
mean(poswords) - mean(negwords).
Raises:
ValueErrorif either anchor pole is empty.ValueErrorif the semantic axis is a zero vector.
Example:
axis = ct.generate_concept_axis(
wv=wv,
poswords=["commit", "persist", "focus"],
negwords=["quit", "avoid", "delay"],
)
5.3 anchor_pole_diagnostics(wv, poswords, negwords, return_frame)
Purpose:
Evaluate whether the positive and negative anchor poles are semantically separated in the embedding space. This follows the WEPA manuscript's anchor-word diagnostic: within-pole cosine similarity should be higher than between-pole cosine similarity.
Parameters:
wv: A word embedding model or compatibleKeyedVectorsobject.poswords: Non-empty list of positive-pole anchor words.negwords: Non-empty list of negative-pole anchor words.return_frame: IfFalse, return a dictionary. IfTrue, return a one-row pandas DataFrame.
Returns:
pos_within_cosine: Average cosine similarity among valid positive-pole anchors.neg_within_cosine: Average cosine similarity among valid negative-pole anchors.between_pole_cosine: Average cosine similarity between positive- and negative-pole anchors.n_poswords,n_negwords: Number of valid anchors found in the embedding vocabulary.separation_expected:Truewhen both within-pole similarities exceed the between-pole similarity.
Example:
diagnostics = ct.anchor_pole_diagnostics(
wv=wv,
poswords=["commit", "persist", "focus"],
negwords=["quit", "avoid", "delay"],
return_frame=True,
)
5.4 semantic_axis_stability(reference_wv, comparison_wvs, poswords, negwords)
Purpose:
Check whether a semantic concept axis is stable across embedding models, such as yearly models in longitudinal research. The function reports two complementary indicators used in the WEPA manuscript: axis orientation stability and anchor rank-order consistency.
Parameters:
reference_wv: Reference embedding model, usually the full-period model.comparison_wvs: A dict or list of target embedding models. Dict keys are used as labels, such as"2016"or"2021".poswords: Non-empty list of positive-pole anchor words.negwords: Non-empty list of negative-pole anchor words.alignment_words: Optional shared vocabulary used for Procrustes alignment. If omitted, all shared words are used.anchor_words: Optional words used for rank-order consistency. If omitted,poswords + negwordsare used.align: IfTrue, align each comparison model to the reference model before diagnostics.return_frame: IfFalse, return a list of dictionaries. IfTrue, return a pandas DataFrame.
Returns:
axis_cosine: Cosine similarity between the comparison semantic axis and the reference semantic axis.anchor_spearman: Spearman rank correlation of anchor-word projection scores between the comparison and reference models.n_anchor_words: Number of shared anchor words used for rank-order consistency.n_alignment_words: Number of shared words used for alignment.aligned: Whether alignment was applied.
Example:
stability = ct.semantic_axis_stability(
reference_wv=full_period_wv,
comparison_wvs={
"2019": wv_2019,
"2020": wv_2020,
"2021": wv_2021,
},
poswords=["commit", "persist", "focus"],
negwords=["quit", "avoid", "delay"],
return_frame=True,
)
Interpretation:
- Higher
axis_cosinemeans the overall semantic direction is more stable. - Higher
anchor_spearmanmeans the internal ordering of anchor words along the axis is more stable. - These diagnostics support longitudinal comparability checks, but they do not prove strict psychometric measurement invariance.
5.5 wepa(wv, text, poswords, negwords, lang, cosine)
Purpose:
Score a text with the Word Embedding Projection Approach. The function constructs or retrieves a cached semantic axis, cleans the text, and projects valid tokens onto the axis.
Parameters:
wv: A word embedding model or compatibleKeyedVectorsobject.text: Input text to score.poswords: Non-empty list of positive-pole anchor words.negwords: Non-empty list of negative-pole anchor words.lang: Text preprocessing language. Common values are"chinese"and"english".cosine: IfFalse, use scalar projection length. IfTrue, use cosine similarity.
Returns:
- A float WEPA score. Higher values indicate stronger alignment with the positive pole.
numpy.nanis returned when no valid text tokens can be scored.
Example:
score = ct.wepa(
wv=wv,
text="I will persist and focus on this goal",
poswords=["commit", "persist", "focus"],
negwords=["quit", "avoid", "delay"],
lang="english",
)
Interpretation:
- Scores indicate construct-related linguistic salience in text.
- Scores should not be interpreted as direct observations of latent psychological states, clinical diagnoses, causal effects, or proof of strict measurement invariance.
5.6 project_text(wv, text, axis, lang, cosine)
Purpose:
Project a text onto an existing semantic axis. Use this when you want to construct the axis once and reuse it for many texts.
Parameters:
wv: A word embedding model or compatibleKeyedVectorsobject.text: Input text to score.axis: A semantic-axis NumPy vector, or a word list that can be averaged into a vector bywv.get_mean_vector.lang: Text preprocessing language. Common values are"chinese"and"english".cosine: IfFalse, return scalar projection length. IfTrue, return cosine similarity to the axis.
Returns:
- The average projection score for valid in-vocabulary tokens.
numpy.nanwhen the axis is invalid or no tokens can be scored.
Example:
axis = ct.generate_concept_axis(wv, ["commit"], ["quit"])
score = ct.project_text(
wv=wv,
text="commit to the goal",
axis=axis,
lang="english",
)
5.7 sematic_projection()
Purpose:
Compute projection scores for a list of words on a concept axis defined by positive and negative anchor words. The function name preserves the current public API spelling.
Parameters:
wv: A word embedding model or compatibleKeyedVectorsobject.words: List of target words to project.poswords: Positive-pole anchor words.negwords: Negative-pole anchor words.cosine: IfFalse, return scalar projection length. IfTrue, return cosine similarity.return_full: IfTrue, return(word, score)pairs. IfFalse, return only scores.
Returns:
- A list of projection scores, or a list of
(word, score)tuples.
Example:
scores = ct.sematic_projection(
wv=wv,
words=["mouse", "horse", "elephant"],
poswords=["large", "big", "huge"],
negwords=["small", "little", "tiny"],
)
5.8 project_word()
Purpose:
Project one word, word list, or concept vector onto another word, word list, or concept vector.
Parameters:
wv: A word embedding model or compatibleKeyedVectorsobject.a: A word string or word list to project.b: A word string, word list, or NumPy vector that defines the projection direction.cosine: IfFalse, return scalar projection length. IfTrue, return cosine similarity.
Returns:
- A float projection score.
Example:
score = ct.project_word(
wv=wv,
a="engineer",
b=["science", "technology"],
)
5.9 sematic_distance()
Purpose:
Compute the Euclidean distance between the mean vectors of two word groups. The function name preserves the current public API spelling.
Parameters:
wv: A word embedding model or compatibleKeyedVectorsobject.words1: First word group.words2: Second word group.
Returns:
- A rounded float distance. Smaller values indicate closer semantic positions.
Example:
distance = ct.sematic_distance(
wv=wv,
words1=["program", "software", "computer"],
words2=["family", "home", "parent"],
)
5.10 divergent_association_task()
Purpose:
Compute a Divergent Association Task style score from a list of words. Higher scores indicate that the selected words are, on average, more semantically distant from one another.
Parameters:
wv: A word embedding model or compatibleKeyedVectorsobject.words: List of submitted words.minimum: Minimum number of valid unique words required. Default is7.
Returns:
- A float DAT score, or
Noneif there are not enough valid words.
Example:
score = ct.divergent_association_task(
wv=wv,
words=["book", "cloud", "machine", "river", "music", "stone", "garden"],
)
5.11 discursive_diversity_score()
Purpose:
Compute a discursive diversity score from a list of words by comparing each word vector with the centroid of the submitted words.
Parameters:
wv: A word embedding model or compatibleKeyedVectorsobject.words: List of words.
Returns:
- A float diversity score.
Example:
score = ct.discursive_diversity_score(
wv=wv,
words=["strategy", "market", "team", "learning"],
)
5.12 procrustes_align()
Purpose:
Align two embedding spaces with an orthogonal Procrustes transformation. This is useful for comparing embeddings trained on different time periods or corpora.
Parameters:
base_wv: Reference embedding model.other_wv: Embedding model to align to the reference model.words: Optional vocabulary used for alignment. If omitted, shared vocabulary is used.
Returns:
- The aligned
other_wvobject.
Example:
aligned_wv = ct.procrustes_align(
base_wv=base_wv,
other_wv=other_wv,
)
Note:
Alignment alone does not prove measurement stability. Use semantic_axis_stability() to report axis orientation and anchor rank-order consistency after alignment.
6. LLM Module
The LLM module supports structured text analysis with large language models.
6.1 ct.llm()
Run an LLM-assisted text analysis task.
result = ct.llm(
text="The user reports a clear goal and strong commitment.",
prompt="Extract the main topic and sentiment.",
output_format={"topic": "string", "sentiment": "string"},
task="structured_analysis",
backend="openai",
model_name="gpt-4o-mini",
)
Function signature:
ct.llm(
text,
prompt=None,
output_format=None,
task=None,
backend=None,
base_url=None,
api_key=None,
model_name=None,
temperature=0,
)
Notes:
- LLM results should be validated for the specific task.
- For research use, report prompts, models, decoding settings, and validation checks.
- LLM outputs should not be treated as ground truth without human or empirical validation.
Parameter notes:
text: the input text to analyze.prompt: task instruction. If omitted, use a built-intaskwhen available.output_format: expected structured output, such as{"sentiment": "string", "score": "number"}.task: named task or template category.backend: model provider or compatible backend.base_url: custom API endpoint for OpenAI-compatible services.api_key: API key when required by the backend.model_name: model identifier.temperature: generation randomness; use low values for reproducible coding tasks.
Structured extraction example:
result = ct.llm(
text="The company increased R&D investment, but short-term profitability declined.",
prompt="Extract the firm's innovation signal and financial pressure signal.",
output_format={
"innovation_signal": "string",
"financial_pressure": "string",
"confidence": "number",
},
task="structured_extraction",
backend="openai",
model_name="gpt-4o-mini",
temperature=0,
)
For batch analysis, store the original text, prompt version, model name, output, and parsing status. This makes later auditing and replication much easier.
6.2 Built-in Prompts
cntext includes prompt templates for common text-analysis tasks. Use them as starting points and adapt them to your research setting.
Example workflow:
prompt = "Classify the sentiment of the text as positive, neutral, or negative."
result = ct.llm(
text="The service is useful but sometimes unstable.",
prompt=prompt,
output_format={"sentiment": "string"},
task="sentiment",
)
Prompt templates are starting points, not validated measurement instruments. For empirical research, test prompts against annotated examples and report inter-rater or benchmark agreement where possible.
Anchor Dictionary Format for WEPA
A WEPA anchor dictionary should document the construct and both semantic poles.
Recommended JSON format:
{
"construct": "goal_commitment",
"description": "Toy anchors for demonstrating a goal commitment semantic axis.",
"language": "english",
"positive_pole": ["commit", "persist", "focus"],
"negative_pole": ["quit", "avoid", "delay"],
"notes": "Example only. Not validated for empirical use."
}
Recommended CSV format:
construct,pole,anchor
goal_commitment,positive,commit
goal_commitment,positive,persist
goal_commitment,positive,focus
goal_commitment,negative,quit
goal_commitment,negative,avoid
goal_commitment,negative,delay
See examples/wepa_anchor_dictionary_format.md for details.
Responsible Use
For WEPA and other construct-scoring workflows:
- Report the corpus, platform, time period, preprocessing steps, embedding model, anchor dictionaries, and validation procedures.
- Treat scores as text-based indicators, not as direct measurement of latent psychological states.
- Do not use scores as clinical diagnoses or causal evidence.
- Validate anchor dictionaries before applying them to new platforms, languages, time periods, or cultural contexts.
- Evaluate measurement stability before making longitudinal comparability claims.
- Avoid claiming universal generalizability or strict measurement invariance without dedicated evidence.
Documentation
The Sphinx documentation is in docs/. Important entry points:
- Introduction:
docs/intro.md - Installation:
docs/install.md - Quick start:
docs/quickstart.md - IO:
docs/io.md - Statistics:
docs/stats.md - Models and embeddings:
docs/model.md,docs/embeddings.md - Semantic projection and WEPA:
docs/mind.md,docs/wepa.md - LLM tools:
docs/llm.md - Plotting:
docs/plot.md - Citation:
docs/cite.md
Citation
Package citation:
@software{cntext,
author = {Deng, Da},
title = {cntext: Text Analysis Tools for Computational Social Science},
url = {https://github.com/hiDaDeng/cntext},
year = {2025}
}
WEPA manuscript citation:
@article{deng2026measuring,
title={Measuring Psychological Constructs from Social Media Text Using the Word Embedding Projection Approach},
author={Deng, Xudong and Li, Yijun},
journal={Behavioral Sciences},
volume={16},
number={5},
pages={762},
year={2026},
doi={10.3390/bs16050762}
}
License
cntext is released under the MIT License. See LICENSE.
関連プロジェクトを探す
読み込み中…