Getting started
Setting up a computing environment for the book’s exercises
The exercise chapters ask you to retrieve data, code text, fit models, and build figures. This page gets you to the point where you can do that. It assumes no prior programming setup.
There are two routes. Start with Colab if you have never installed a programming environment, if you are on a locked-down institutional laptop, or if you simply want to be running code in the next five minutes. Set up locally when you are working with data you cannot upload to a third party, when your corpus is large, or when you want a permanent environment that you control.
The book’s exercises are language-agnostic, and every one of them can be completed in R or Stata. This site uses Python for its worked examples because it has the widest coverage of the specific tools the later chapters need (transformer models, topic modeling libraries, network analysis). If you already work in R, read the Python here as pseudocode and use the R equivalents listed in the tool guides.
Route 1: Zero-install with Google Colab
Google Colab runs Python notebooks in your browser on Google’s machines. Nothing is installed on your computer, the common data-science libraries are preinstalled, and it is free for the scale of work in this book.
First run, start to finish:
- Go to colab.research.google.com and sign in with a Google account.
- Choose File → New notebook.
- Click into the empty code cell, paste the lines below, and press Shift+Enter.
import pandas as pd
papers = pd.DataFrame({
"doc_id": ["d001", "d002", "d003"],
"title": ["Access barriers in rural districts",
"A scalable optimization framework",
"Community-based participation and equity"],
"year": [2019, 2021, 2022],
})
papers["title_length"] = papers["title"].str.split().str.len()
papersIf a small table appears underneath the cell, your environment works. That is the whole setup.
What to know before you rely on it:
- Sessions are temporary. A Colab machine is reclaimed after a period of inactivity and everything in its local storage disappears. Save anything you care about to Google Drive (
from google.colab import drive; drive.mount('/content/drive')) or download it. - Uploading data means uploading data. Do not put confidential, restricted, or IRB-protected material into a hosted notebook without checking your institution’s rules and the terms of the service. This is a research-ethics question, not just an IT one (see Chapter 11).
- Install extra packages per session with
!pip install packagenameat the top of the notebook. It has to be rerun each time the session restarts.
Route 2: A local environment
A local setup gives you a stable, private, reproducible environment. The steps below use Miniconda, which installs Python and a package manager together and does not disturb any Python your operating system already depends on.
Install Miniconda from the official installer page for your operating system.
Create a project environment. Open a terminal (Terminal on macOS/Linux, Anaconda Prompt on Windows) and run:
conda create -n cssprimer python=3.11 conda activate cssprimerThe environment name appears in your prompt when it is active. Activate it every time you work on this project.
Install the packages the book’s exercises use:
pip install pandas pyarrow scikit-learn matplotlib seaborn \ jupyterlab networkx gensim bertopic requestsStart JupyterLab and create a notebook to check the install:
jupyter labRun the same three-line pandas snippet from the Colab section above.
Record what you installed. From the active environment:
pip freeze > requirements.txtCommit that file with your project. This is the lock file discussed in Chapter 9: it is what lets you (or a replicator) rebuild this exact environment later.
JupyterLab is enough for everything in this book. If you prefer a full editor, VS Code with the Python and Jupyter extensions is the most common choice and integrates with the AI coding assistants discussed in Chapter 6.
R and Stata users
The equivalent moves are renv::init() for a project-local R library plus renv::snapshot() for the lock file, or a documented version statement and package list in Stata. The principle from Chapter 9 is identical across languages: pin what you installed, record it in the project, and never rely on “latest version.”
Getting access to an AI model
Several exercises (Chapter 4’s screening, Chapter 6’s LLM coding, Chapter 8’s validity audit) call a language model. You have three kinds of options, and the right one depends on your budget, your data, and your institution.
Option A: Your institution’s provided access
Many universities now provide licensed access to a commercial model with a data protection agreement in place. This is usually the best first stop: it is free to you and the institutional agreement may permit data that a personal account would not. Ask your library, research computing group, or IT service desk.
Option B: A commercial API
Providers such as OpenAI, Anthropic, and aggregators such as OpenRouter (one interface across many models) sell access by usage. For the corpus sizes in this book, coding a few thousand abstracts typically costs in the range of a few dollars, but check current prices before running a batch.
Handling keys safely. An API key is a credential that can spend your money. Never paste one into a notebook cell, a script you will commit, or a chat window. Put it in an environment variable or a .env file that is listed in your .gitignore:
import os
api_key = os.environ["OPENAI_API_KEY"] # set in your shell, not in the codeControlling cost. Set a spending cap in the provider’s dashboard before your first run. Then develop your prompt against 20 documents, not 20,000; only scale up once the prompt is stable and audited (Chapter 6).
Option C: A local open-weight model
Ollama runs open-weight models on your own machine with a single command. Nothing leaves your computer, there is no per-call cost, and the model version is pinned by definition, which is a real reproducibility advantage (Chapter 9). The trade-offs are that you need adequate hardware and that smaller open models are generally less accurate on nuanced coding tasks than the largest commercial ones. For confidential data, this may be the only defensible option.
# after installing Ollama
ollama pull llama3.1
ollama run llama3.1 "Summarize the following abstract in one sentence: ..."Model name, version, date, and settings are part of your method, not incidental configuration. Chapter 6 develops this as the promptbook; Chapter 9 explains why an undocumented model version can make an analysis impossible to reproduce.
Where to go next
- New to text data? → Working with text data
- Never trained a classifier? → Supervised learning, gently
- About to write your first coding prompt? → Prompting and its failure modes
- Setting up the project folder from Chapter 2? → Project templates