W2:R 與 Python 的文本前處理與協作流程(Text Preparation in R and Python)
W1 談「文本可以當作資料」;W2 動手把文字變成資料:挑文件、清理、切字(tokenize)、建 DFM(document-feature matrix),並且每一步都問:「這個選擇讓我的量測失去了什麼?」
本週學習目標
投影片 2 列了四個目標,最後一個(清理、切字、建 DFM、評估前處理選擇)是本教材的主軸。老師也提醒:這是提前介紹 W4 的內容,W4 會在這個基礎上做字典、情緒分析與驗證。
- 在 RStudio 與 Positron 設定好 R 與 Python 的文本分析環境。
- 用 GitHub 管理程式碼,用共用的 Overleaf 專案繳交書面作業。
- 檢查給定語料與自己專題資料的可行性:涵蓋範圍(coverage)、metadata、取得方式(access)。
- 清理並切字、建立 DFM,並評估前處理選擇對量測的影響。
讀完一章後,回來勾選你覺得已經做得到的目標(只存在這台瀏覽器):
投影片的 GitHub/Overleaf 協作部分只在學習目標中出現,沒有獨立頁面,本教材不另行補寫操作細節。安裝與開啟 R、Python、RStudio、Positron 的步驟在第 02 章與第 10 章。
概念地圖:從一堆文字到一張矩陣
點擊方塊看說明。流程整理自投影片 14(Welbers et al. 2017 的分析步驟圖)與投影片 15(本課使用的物件)。
靜態摘要:研究問題與母體 → 選文件(觀察到的語料)→ 匯入與編碼檢查 → 字串清理(stringr)→ corpus(文字+metadata)→ tokens(切字、片語、停用字)→ DFM(計數、二元、TF-IDF;修剪)→ 分析(字典、分類、主題模型、縮放、相似度);KWIC 讓你隨時回到原文檢查。
兩份練習資料
- d1:Health workers need health services.
- d2:The government supports health services.
- d3:Workers do not support the policy.
- d4:The government supports the policy.
刻意做得很短,讓你能檢查每一個 token、驗證每一個計數。第 05、06、08 章都用它。
lab/Data/hc_sample_1945_2025.rds:5,000 筆下議院發言(speech contributions),1945–2025。- 13 個欄位:date、agenda、speechnumber、speaker、party、party.facts.id、chair、terms、text、speech_url、parliament、iso3country、party_raw。
- 資料檔屬性記載的抽樣種子是 20260706;抽樣框排除了議長(chair)發言、缺講者/政黨/文字的發言(R
str(hoc)實查)。 - 5,000 是發言筆數,不是議員人數:同一位議員可以發言很多次。
怎麼使用這份教材
- 左側是 15 章;右側(寬螢幕)是投影片對照面板,捲到標有「投影片 N」的段落會自動翻到那一頁;點徽章也可以。
- 第 10–12 章的 R 程式碼與輸出是本機實際執行
Lab_Session_W2_Answers.R的結果(R 4.5.3、quanteda 4.5.1、quanteda.textstats 0.97.2、quanteda.textplots 0.96.1、stringr 1.6.0、dplyr 1.2.1、ggplot2 4.0.3;Linux aarch64),並與老師答案 HTML 裡的輸出逐一對照。 - 標示「補充(非講義內容)」的段落、玩具示範是額外說明,不是投影片內容。
- 互動元件分三種:真實資料型(直接用 Lab 的 5,000 筆資料匯出)、玩具直覺型(小例子)、練習型(作答區、翻牌卡、判斷題、填寫器)。
- 老師的自學建議:逐段跑 Lab、讀每一個輸出;有問題時帶著練習題號、相關程式碼、輸出或錯誤訊息來問。
自我檢查
nrow(hoc) 的 5000 是發言筆數,不是議員人數。QTA 五原則與選擇文件
前處理之前,偏誤就已經開始了。這一章談:文字從哪裡來、誰的文字比較容易被留下、一份「文件」是什麼。
量化文本分析的五個原則
- 領域知識定義研究問題與相關證據(Domain knowledge defines the research problem and relevant evidence)。
- 人的判斷引導詮釋與驗證(Human judgment guides interpretation and validation)。
- 發現與檢驗要分成不同階段(Discovery and testing require distinct stages)。
- 任務決定哪些方法有用(The task determines which methods are useful)。
- 驗證是評估「這個量測是否符合你的主張」(Validation evaluates whether the measure fits the claim)。
來源:Schoonvelde (2026);Grimmer et al. (2022)。
電腦只會數字;數什麼、怎麼解讀、數出來的東西能不能支持你的結論,都是研究者的責任。這五條原則會在每一個前處理選擇上重複出現。
選擇文件:Grimmer et al. (2022) 第 4 章
課堂例子:量測「對咖啡表達的偏好」。
| 設計選擇 | 例子 |
|---|---|
| 目標母體(Target population) | 某個月份、泰文、公開、與咖啡有關的貼文 |
| 關心的量(Quantity of interest) | 這些貼文中表達正面咖啡偏好的比例 |
| 觀察到的語料(Observed corpus) | 一個平台 API 加上一組指定關鍵字搜尋所回傳的貼文 |
Found data(現成資料):要記錄文字是怎麼產生、保存、取回的。下一步是檢查「蒐集過程漏掉了什麼」。
選擇偏誤在前處理之前就開始了
| 偏誤來源 | 例子 | 研究後果 |
|---|---|---|
| 資源(Resources) | 經費充足的團體保存更多文件 | 現有文本過度代表某些行動者 |
| 誘因(Incentives) | 政治人物策略性地公開發言 | 公開陳述不同於私下信念 |
| 媒介(Medium) | 平台限制長度或能見度 | 媒介形塑了表達 |
| 檢索(Retrieval) | 只搜尋 “economy” | 用其他字表達的相關文本消失 |
互動:這是哪一種選擇偏誤?
下面的情境是本教材自擬的練習(補充,非講義內容);分類依投影片 5 的四種來源。選一個答案就會顯示說明。
語料邊界與文件單位
| 決定 | 例子 | 要記錄什麼 |
|---|---|---|
| 母體(Population) | 國會發言(Parliamentary speech contributions) | 院別、行動者、日期 |
| 納入規則(Inclusion) | 選定辯論中的所有發言 | 規則與排除項目 |
| 文件單位(Document unit) | 每列一筆發言 | 段落是怎麼切的 |
| 識別碼(Identifier) | 持久的 doc_id | 連回原始來源與 metadata |
把單位改成「講者 × 日」或「政黨 × 年」,比較本身就改變了。 第 10 章的 Lab 會實際示範:81 篇 Engagements 發言改成句子單位後變成 364 份「文件」。
來源與匯入路徑
| 來源 | 常見路徑(R 套件) | 第一個要檢查的事 |
|---|---|---|
| 現成語料 | 下載+codebook | 涵蓋範圍與抽樣 |
| TXT、CSV、TSV | readr、data.table、base R | 編碼與欄位 |
| JSON 或 API | jsonlite、httr2 | 分頁與識別碼 |
| HTML 或 XML | rvest、xml2 | 版型雜訊(boilerplate)與結構 |
| PDF 或 DOCX | pdftools、readtext | 閱讀順序與文件邊界 |
掃描的 PDF 可能要先 OCR 才有可用的文字。
自我檢查
工具版圖:quanteda、UDPipe、spaCy、Flair,以及 R+Python
R 可以準備文字、呼叫其他工具,再分析它們回傳的標註或向量。工具會互相重疊,能力取決於語言、模型與任務。
2017 年的 R 文本分析工具箱
投影片 8 重製了 Welbers, Van Atteveldt & Benoit (2017) 的 Table 1(文本分析操作與對應 R 套件),並註明:這是 2017 年的歷史概覽,套件分工與 API 之後已經改變。原文 Table 1 把操作分三段:資料準備(importing text、string operations、preprocessing、DTM、filtering and weighting)、分析(dictionary、supervised/unsupervised machine learning、text statistics)、進階主題(advanced NLP、word positions and syntax)。(Welbers et al. 2017, p. 247)
| 操作(Welbers et al. 2017, Table 1) | 文中示範套件 | 替代套件(節錄) |
|---|---|---|
| importing text | readtext | jsonlite, XML, antiword, readxl, pdftools |
| string operations | stringi | stringr |
| preprocessing/DTM/filtering and weighting | quanteda | tm, tidytext, Matrix 等 |
| unsupervised machine learning | topicmodels | quanteda, stm, austin, text2vec |
| advanced NLP | spacyr | coreNLP, cleanNLP, koRpus |
2017 之後:標註與 embeddings
| 工具/從 R 存取 | 模型類型 | 輸出與用途 |
|---|---|---|
| UDPipe 1:R 套件 udpipe | 以 treebank 訓練的監督式標註管線 | tokens、lemmas、POS、依存關係標籤 |
| UDPipe 2:R+REST API | 使用 contextual embeddings 的神經網路標註 | 語言標註;現行模型使用 BERT 類表示 |
| Flair:R reticulate+Python(flaiR;Liao et al., 2023) | contextual string embeddings 或 Transformer embeddings | 字/文件向量;NER、tagging、分類模型 |
FlairEmbeddings 用字元語言模型;TransformerWordEmbeddings 用 BERT 之類的模型。
quanteda、UDPipe、spaCy、Flair
| 工具/存取 | 主要重點 | 典型輸出 |
|---|---|---|
| quanteda(R) | 語料管理與特徵分析 | corpus、tokens、DFM;KWIC 與 TF-IDF |
| UDPipe(R/API) | 用訓練好的模型做語言標註 | tokens、lemmas、POS、UD 依存標籤 |
| spaCy(Python) | 可設定的 NLP 管線 | tokens、POS、依存關係、命名實體 |
| Flair(Python;flaiR 是 R wrapper) | embeddings 與神經網路任務模型 | 向量;實體標籤、POS、文本類別 |
這些工具可以合作:例如把 lemma 或挑選過的標註變成 quanteda DFM 的特徵(第 07 章投影片 44 有程式示意)。
翻牌卡:這個工具/函式是做什麼的?
卡片背面內容依投影片 9–10、19、15 與 Lab 的函式表;頁碼標在卡上。
R 與 Python 在同一個流程裡
投影片 11 的可能應用:比較政策陳述的意義。
靜態版:Prepare in R(stringr、quanteda:清理文字並保留 document ID)→ Represent in Python(sentence-transformers:把文本編成語意向量)→ Evaluate in R(統計模型與圖:驗證相似度並詮釋型態)。每一階段都跟著研究問題走。
- R 的
reticulate匯入 Python 模組、呼叫它的函式。 - 老師博士班期間(2018–2022)常用 reticulate。
- 它會在 R 與 Python 之間轉換支援的物件。
- 除了 R 套件,也要記錄 Python 環境。
- R 與 Python 腳本透過 CSV 或 Parquet 等檔案交換資料。
- 穩定的 document ID 把輸入與輸出連起來。
- 每次交接都要檢查列順序、編碼與資料型別。
投影片 12 的結語:IDE 負責組織工作;物件或檔案交換負責連接兩種語言。
Positron:一個 IDE 給 R 與 Python
- 2022 年 RStudio 公司改名 Posit,反映它對跨語言資料科學的支援。
- Posit 開發了 Positron,用於多語言資料科學;R 與 Python 內建支援,有 console 與資料檢視。
- RStudio IDE 仍是另外持續維護的產品。
- 本課的課堂範例使用 R。
自我檢查
文本分析的步驟、四種物件與匯入檢查
分析可以走「矩陣」路線(DFM),也可以保留 token 的位置或其他表示。先搞清楚你手上是哪一種物件。
文本分析操作的順序
投影片 14 重製 Welbers et al. (2017) 的 Figure 1(Order of text analysis operations for data preparation and analysis, p. 247)。投影片的提醒:分支很重要——分析可以用矩陣、token 位置或其他表示。Welbers 等人主要談 bag-of-words,即「只用每篇文字的字頻、忽略字的位置」(p. 246),並在進階主題談保留字位置與句法的做法(pp. 258–261)。
本課使用的四種物件
| 物件 | 內容 | 用途 |
|---|---|---|
| Data frame | 文字、識別碼、metadata | 匯入檢查與合併(joins) |
corpus | 文字+文件變數(docvars) | 取子集、讀 metadata |
tokens | token 序列(保留順序) | 片語比對、上下文檢查(KWIC) |
dfm | 文件 × 特徵 | 計數與加權表示 |
stringr 處理字串;quanteda 提供 corpus → tokens → DFM 的流程。
- data.frame:Lab 的
hoc,一列一筆發言,text 與 metadata 都是欄位。 - corpus:
corpus(hoc, text_field = "text");其他欄位變成 docvars,仍是 5,000 份文件。 - tokens:每份文件變成字的序列;可以
tokens_compound()、kwic()。 - dfm:只剩計數,順序消失;可以
dfm_group()、dfm_trim()、textstat_keyness()。
匯入檢查與編碼
texts <- readLines("data/speeches.txt", encoding = "UTF-8")
length(texts)
head(texts)- 確認來源的編碼,不要看起來對就猜。
- 匯入後檢查重音字母與中文字。
- 數一數缺漏的文字與重複的識別碼。
- 確認一列是一行、一段,還是一整份文件。
加上 encoding = "UTF-8" 參數,不能修復來源編碼被認錯的文字。
Lab 的搭配詞輸出裡出現 sinn fã(count 15),同一份表也有 sinn fein(count 17)。「Féin」的 é 很可能在資料的上游處理時被以錯誤的編碼解讀而變成亂碼(mojibake),結果同一個政黨名稱被拆成兩個特徵。這正是投影片 16 要你匯入後「檢查重音字母」的原因。(輸出見第 11 章 find_collocations;成因判斷為本教材推論,非講義內容。)
一個國會發言例子
| 欄位 | 投影片中的值 |
|---|---|
| Date | 1997-01-20 |
| Speaker | William Hague |
| Party | Conservative |
| Agenda | Public Expenditure [Oral Answers To Questions > Wales] |
文字中包含 [Interruption.]、DRAMATICALLY 與 !!!。投影片問:哪些是 metadata、哪些是有意義的語言、哪些是記錄慣例(recording conventions)?
互動:metadata、語言,還是記錄慣例?
每一個元素選一個類別。按下後會顯示投影片 18 建議的處理方式與「可能失去的資訊」。注意:有些元素的答案取決於研究問題。
| 元素 | 可能的處理 | 牽涉的資訊 |
|---|---|---|
| 講者與政黨 | 存成 metadata | 誰在說話 |
[Interruption.] | 移除,或抽出成一個指標變數 | 議會中的互動 |
| 大小寫 | 保留或轉小寫 | 專有名詞與強調 |
| 數字 | 保留、正規化或移除 | 年份、預算、百分比 |
| 重複標點 | 保留或簡化 | 修辭上的強調 |
永遠保留一份未修改的原始文字。
自我檢查
[Interruption.] 最合理的處理是?清理取決於研究問題:stringr 與正規表示式
清理不是中性的。每一條規則都會留下某些資訊、丟掉某些資訊;所以要有「稽核軌跡」(audit trail)。
stringr 的字串操作
| 函式 | 用途 | 例子 |
|---|---|---|
str_detect() | 測試 pattern 是否出現(TRUE/FALSE) | 標出含中括號註記的文字 |
str_extract() | 取出第一個符合的片段 | 抽出年份 |
str_remove_all() | 刪除所有符合的片段 | 刪除選定的註記 |
str_replace_all() | 取代符合的片段 | 統一分隔符號 |
str_squish() | 正規化空白 | 去掉重複空格與頭尾空白 |
str_to_lower() | 改變大小寫 | 合併大小寫變體 |
Lab 另外用到 str_which()(哪幾個位置有符合)、str_locate()/str_locate_all()(符合的起訖字元位置)、str_extract_all()、str_to_title();見第 10 章。
中括號 pattern 與意外刪除
s <- "Trade [Commons] and jobs [Wales]" str_remove_all(s, "\\[.*\\]") str_remove_all(s, "\\[[^\\[\\]]*\\]") |> str_squish()
> s <- "Trade [Commons] and jobs [Wales]" > str_remove_all(s, "\\[.*\\]") [1] "Trade " > str_remove_all(s, "\\[[^\\[\\]]*\\]") |> str_squish() [1] "Trade and jobs"
投影片:第二個 pattern 可以處理分開、沒有巢狀的中括號群組。
互動:貪婪 vs. 非貪婪的中括號刪除
| 規則 | 結果 |
|---|---|
str_remove_all(s, "\\[.*\\]") | |
str_remove_all(s, "\\[[^\\[\\]]*\\]") |> str_squish() | |
Lab 的規則 str_replace_all(s, "\\s*\\[.*\\]", "") |
有稽核軌跡的清理範例
agenda_raw <- " Export Trade [Commons] -- vol. 407 "
agenda_clean <- agenda_raw |>
str_remove_all("\\[[^\\[\\]]*\\]") |>
str_to_lower() |>
str_replace_all("[^[:alnum:][:space:]]", " ") |>
str_squish()
agenda_clean> agenda_raw <- " Export Trade [Commons] -- vol. 407 "
> agenda_clean <- agenda_raw |>
+ str_remove_all("\\[[^\\[\\]]*\\]") |>
+ str_to_lower() |>
+ str_replace_all("[^[:alnum:][:space:]]", " ") |>
+ str_squish()
> agenda_clean
[1] "export trade vol 407"這條規則保留數字、移除標點;別的任務可能需要不同的規則。 「稽核軌跡」的意思是:清理後的欄位另存新欄(Lab 用 agenda_clean),原始欄位保留,隨時可以對照。
互動:regex 遊樂場(Lab 真實議程標籤)
資料是 Lab 的 hoc$agenda(R 匯出的 4,000 多個不同標籤與次數;另有 206 筆 NA)。輸入 pattern,看看有幾筆發言符合,並列出前 12 個標籤(符合處加底色)。JS 的 regex 與 R/stringr(ICU)大致相同,但不完全一樣(例如 POSIX 類 [:alnum:] 在 JS 不支援);正式結果以 R 為準。在這裡輸入一個反斜線就好(JS 寫法),R 字串裡要寫兩個。
試試看:比較 war 與 \bwar\b,多出來的是哪些標籤?
war 也會比到 “warfare”、“towards”、“award”、“Stewart” 之類包含這三個字母的字;\bwar\b 只比獨立的字,但 “post-war” 仍然算,因為連字號被當成字的邊界。Lab 的 word_boundary_examples 正是示範這件事(第 10 章)。要不要把 post-war 算進去,取決於研究問題。
自我檢查
str_remove_all("Trade [Commons] and jobs [Wales]", "\\[.*\\]") 的結果是?.* 從第一個 [ 吃到最後一個 ]。" Export Trade [Commons] -- vol. 407 " 的結果是?agenda_clean,而不是覆蓋 agenda?四句小語料:corpus、tokens 與 types
用四句短到可以逐字檢查的文字,看清楚每一步 R 做了什麼。本章所有 R 輸出都是本機實際執行投影片原始碼(week2.qmd 的 setup chunk)得到的。
建立 corpus
library(quanteda)
library(stringr)
raw <- data.frame(
doc_id = c("d1", "d2", "d3", "d4"),
text = c("Health workers need health services.",
"The government supports health services.",
"Workers do not support the policy.",
"The government supports the policy."),
stringsAsFactors = FALSE
)
corp <- corpus(raw, docid_field = "doc_id", text_field = "text")
docnames(corp)> library(quanteda)
Package version: 4.5.1
Unicode version: 17.0
ICU version: 78.3
Parallel computing: 2 of 2 threads used.
See https://quanteda.io for tutorials and examples.
> library(stringr)
> raw <- data.frame(
+ doc_id = c("d1", "d2", "d3", "d4"),
+ text = c("Health workers need health services.",
+ "The government supports health services.",
+ "Workers do not support the policy.",
+ "The government supports the policy."),
+ stringsAsFactors = FALSE
+ )
> corp <- corpus(raw, docid_field = "doc_id", text_field = "text")
> docnames(corp)
[1] "d1" "d2" "d3" "d4"每一列提供一份文字;其餘欄位變成文件變數(document variables, docvars)。這裡 docid_field = "doc_id" 讓文件名稱就是 d1–d4,而不是預設的 text1–text4。
Lab 的 corpus(hoc, text_field = "text") 沒有指定 docid_field,所以文件名稱是 text1…text5000(見第 10 章 summary 輸出)。如果之後要跟 Python 或其他檔案交接,投影片 12 建議用穩定的 document ID。
tokens、types 與詞彙
文字:“Health services need health workers.”
| 表示方式 | Tokens | 不同的 types |
|---|---|---|
| 保留大小寫與標點 | 6 | 6 |
| 轉小寫、移除標點 | 5 | 4 |
正規化之後:health, services, need, health, workers。token 是一次出現;type 是在你選定的表示方式下一個不同的形式。
t24 <- "Health services need health workers." t_keep <- tokens(t24) t_norm <- tokens(t24, remove_punct = TRUE) |> tokens_tolower() c(tokens = ntoken(t_keep), types = ntype(t_keep)) c(tokens = ntoken(t_norm), types = ntype(t_norm)) as.character(t_norm)
> t24 <- "Health services need health workers."
> t_keep <- tokens(t24)
> t_norm <- tokens(t24, remove_punct = TRUE) |> tokens_tolower()
> c(tokens = ntoken(t_keep), types = ntype(t_keep))
tokens.text1 types.text1
6 6
> c(tokens = ntoken(t_norm), types = ntype(t_norm))
tokens.text1 types.text1
5 4
> as.character(t_norm)
[1] "health" "services" "need" "health" "workers" 本機 R 驗證:ntoken()/ntype() 得到 6/6 與 5/4,與投影片 24 一致。保留大小寫時 “Health” 與 “health” 是兩個 type,句點也是一個 token。
互動:token/type 計數器
JS 用簡化的切字規則(以空白與標點切開;連字號、縮寫的處理與 quanteda 不同),只用來建立直覺。兩個勾都不勾 = 6/6;兩個都勾 = 5/4。
R 文本分析的 token vs. LLM 的 token
| 比較 | 常見的 R 文本分析流程 | 典型的 LLM 流程 |
|---|---|---|
| 常見單位 | 字;也可以是字元或句子 | 常是子詞(subwords);也可能是整個字、字元或位元組單位 |
| 切法取決於 | 套件、tokenizer 與你的設定 | 模型的 tokenizer 與詞彙表 |
| 主要用途 | 字數計數、DFM、TF-IDF、主題模型 | 當作模型輸入與文字生成的 token ID |
一個字可以變成好幾個 LLM token。R 可以呼叫任一種 tokenizer;流程決定單位。
明確寫出選擇的切字
toks <- tokens(corp, remove_punct = TRUE) |> tokens_tolower() as.list(toks)[[1]]
> toks <- tokens(corp, remove_punct = TRUE) |> + tokens_tolower() > as.list(toks)[[1]] [1] "health" "workers" "need" "health" "services"
d1 的五個 token:health, workers, need, health, services。文字裡有連字號、網址、縮寫或非拉丁文字時,一定要看輸出。(Lab 的例子:議會文字常見的 “right hon.” 會讓句子切錯,見第 10 章。)
自我檢查
前處理的選擇與資訊流失
投影片 27 的關鍵問題:這個選擇如何影響你想要的量測?不是「標準做法是什麼」。
前處理選擇與資訊流失
| 選擇 | 可能的好處 | 可能的損失 |
|---|---|---|
| 轉小寫 | 合併 Health 與 health | 專有名詞的區分 |
| 移除停用字 | 減少高頻的功能字 | 否定、寫作風格 |
| stemming 或 lemmatization | 合併某些詞形 | 意義上的差別 |
| 修剪罕見特徵 | 縮小詞彙量 | 罕見但重要的概念 |
停用字與否定
sw <- setdiff(stopwords("en"), c("not", "no", "nor"))
toks_content <- tokens_remove(toks, pattern = sw)
as.character(tokens_remove(toks, pattern = stopwords("en"))["d3"])
as.character(toks_content["d3"])
length(stopwords("en"))> sw <- setdiff(stopwords("en"), c("not", "no", "nor"))
> toks_content <- tokens_remove(toks, pattern = sw)
> as.character(tokens_remove(toks, pattern = stopwords("en"))["d3"])
[1] "workers" "support" "policy"
> as.character(toks_content["d3"])
[1] "workers" "not" "support" "policy"
> length(stopwords("en"))
[1] 175| 套用在 d3 的規則 | 剩下的 tokens |
|---|---|
| 標準英文停用字表 | workers support policy |
| 保留否定的停用字表 | workers not support policy |
保留 not 保住了一個線索;但 unigram 模型仍需要某種方式使用它的作用範圍(scope)。 本機輸出確認 stopwords("en") 有 175 個字,not、no、nor 都在裡面。
詞袋(bag-of-words)表示法
DFM 每份文件一列、每個特徵一欄。下面是用「保留否定」的 tokens 建出的計數 DFM 中選出的幾欄:
x <- dfm(toks_content)
as.matrix(x[, c("health", "workers", "government", "policy", "not")])> x <- dfm(toks_content)
> as.matrix(x[, c("health", "workers", "government", "policy", "not")])
features
docs health workers government policy not
d1 2 1 0 0 0
d2 1 0 1 0 0
d3 0 1 0 1 1
d4 0 0 1 1 0與投影片 29 的表完全一致(d1 的 health = 2)。特徵也可以代表片語或其他類別。
字數還原不了什麼
“Workers support government.” 與 “Government support workers.” 轉小寫後的 unigram 計數完全相同:
wo <- tokens(c(a = "Workers support government.", b = "Government support workers."),
remove_punct = TRUE) |> tokens_tolower() |> dfm()
as.matrix(wo)> wo <- tokens(c(a = "Workers support government.", b = "Government support workers."),
+ remove_punct = TRUE) |> tokens_tolower() |> dfm()
> as.matrix(wo)
features
docs workers support government
a 1 1 1
b 1 1 1- 字的順序告訴你誰支持誰。
- 否定需要字與字之間的關係。
- 有歧義的字需要上下文。
- 反諷可能取決於句子以外的語境。
N-grams 與句法能保留一些額外資訊。(上面兩列計數相同的 R 驗證是本教材補充執行的。)
多字詞(multiword expressions)
phrase_toks <- tokens(
"We support the armed forces.",
remove_punct = TRUE
) |> tokens_tolower()
tokens_compound(
phrase_toks,
pattern = phrase("armed forces")
)> phrase_toks <- tokens(
+ "We support the armed forces.",
+ remove_punct = TRUE
+ ) |> tokens_tolower()
> tokens_compound(
+ phrase_toks,
+ pattern = phrase("armed forces")
+ )
tokens of 1 document (4 tokens, 4 types).
text1 :
[1] "we" "support" "the" "armed_forces"armed_forces 變成單一特徵。先偵測片語,再刪除可能是片語一部分的字。 Lab 用同樣的方法把 “Prime Minister”、“House of Commons”、“European Union”、“National Health Service” 合併(第 11 章)。
bigram 與操作順序
tokens("Workers do not support the policy.",
remove_punct = TRUE) |>
tokens_tolower() |>
tokens_ngrams(n = 2)
tokens("Workers do not support the policy.",
remove_punct = TRUE) |>
tokens_tolower() |>
tokens_remove(stopwords("en")) |>
tokens_ngrams(n = 2)> tokens("Workers do not support the policy.",
+ remove_punct = TRUE) |>
+ tokens_tolower() |>
+ tokens_ngrams(n = 2)
tokens of 1 document (5 tokens, 5 types).
text1 :
[1] "workers_do" "do_not" "not_support" "support_the" "the_policy"
> tokens("Workers do not support the policy.",
+ remove_punct = TRUE) |>
+ tokens_tolower() |>
+ tokens_remove(stopwords("en")) |>
+ tokens_ngrams(n = 2)
tokens of 1 document (2 tokens, 2 types).
text1 :
[1] "workers_support" "support_policy" 投影片的 bigram:workers_do, do_not, not_support, support_the, the_policy。如果原本的相鄰關係重要,要在移除停用字之前產生 bigram。先刪字會造出原本並不相鄰的配對。 上面第二段輸出(本教材補充執行)示範反過來做的後果:標準停用字表刪掉 do、not、the 之後,產生了原文中不存在的 workers_support,否定完全消失。
搭配詞與語法特徵
| 特徵策略 | 例子 | 需要的判斷 |
|---|---|---|
| 已知片語 | armed_forces | 哪些片語重要? |
| 統計搭配詞(collocation) | 候選如 northern_ireland | 這個關聯在實質上有用嗎? |
| 依詞性(POS)挑選 | 名詞、動詞、形容詞 | 哪些語法角色符合任務? |
高頻或高關聯的字對只是候選特徵;加進量測規則之前要先檢查它的用法。 Lab 的真實輸出裡,northern ireland 出現 338 次、λ ≈ 12.41(第 11 章)。
stemming 與 lemmatization
| 方法 | 例子 | 限制 |
|---|---|---|
| Stemming | studies → studi | stem 可能不是字典裡的字 |
| Lemmatization | studies 可能 → study | 準確度取決於語言與上下文 |
| 明確替換 | 把 forces 對應到 force | 只處理你提供的對應 |
兩種方法都不保證語意分組正確。用完整字建的字典,可能比不到 stem 過的特徵。 Welbers et al. (2017, p. 252) 另提醒順序問題:先 stem 再移除停用字,“during” 會變成 “dure”,就比不到停用字表裡的 “during”。
互動:前處理開關實驗室(四句小語料)
每個開關對應一個 quanteda 步驟。預設設定 = 投影片 26–28、46 的設定(移除標點、轉小寫、移除「保留否定」的停用字表),應得到 4 × 9 的 DFM。停用字表是 R 匯出的 stopwords("en")(175 字)。JS 只是重現示範,正式結果以 R 為準。
自我檢查
多語言:英文的空白不是通用的字界
中文、日文、泰文需要斷詞模型;停用字與詞形工具都跟語言綁在一起。UDPipe 給你 token、詞性(POS)與依存關係(dependency)。
投影片 38–42 的 UDPipe 輸出是老師在投影片原始檔(week2.qmd)裡轉錄自先前簡報 HTML 的模型預測,投影片 36 也註明是「講者示範:詮釋準備好的模型輸出」。本教材沒有重新執行 UDPipe(需要另外下載語言模型,泰文還要呼叫 UDPipe 2 的 REST API),以下互動用的就是投影片上的這些輸出,每一筆都標了頁碼。
語言與模型的要求
- 英文的空白不是通用的字界。
- 中文斷詞需要檢查。
- 停用字與詞形工具都是語言專屬的。
- DFM 可以用字或片語特徵。
- 預訓練模型期待它自己的 tokenizer。
- 保留那個模型需要的輸入區分。
BoW 的前處理配方不應自動變成 LLM 的輸入配方。
UDPipe 模型:日文、中文、泰文
| 輸入語言 | 從 R 存取 | 模型 |
|---|---|---|
| 日文 | udpipe:本機 UDPipe 1 | japanese-gsd(UD 2.5) |
| 繁體中文 | udpipe:本機 UDPipe 1 | chinese-gsd(UD 2.5) |
| 泰文 | httr2:UDPipe 2 API | thai-tud(UD 2.17) |
- 三者都提供斷好的
token與預測的upos(POS)。 - 依存句法分析(dependency parsing)加上 head 與關係標籤。
lemma是預測的基本形;這個泰文模型回傳_(無法提供)。
用 UDPipe 標註 UTF-8 文字
library(udpipe)
# Set model_path to a downloaded Chinese-GSD model.
zh_model <- udpipe_load_model(model_path)
ann_zh <- udpipe_annotate(zh_model, x = "我喜歡咖啡。",
doc_id = "zh_coffee", parser = "default") |> as.data.frame()
ann_zh[c("token_id", "token", "upos",
"head_token_id", "dep_rel")]parser = "default"在 token 與 POS 之外加上依存句法。head_token_id指出 head;dep_rel標示關係。Head 0 代表句子的 root。- 中文用 chinese-gsd;英文用 english-ewt;泰文用 R+UDPipe 2 API。
互動:斷詞與依存檢視器(投影片 38–42 的輸出)
投影片 38 的斷詞比較(不計標點):泰文 3 個 token(ฉัน PRON/ชอบ VERB/กาแฟ NOUN),模型找出了字界;日文 6 個 token(私 PRON/は ADP/コーヒー NOUN/が ADP/好き ADJ/です AUX),助詞與助動詞是獨立的 token;中文 3 個 token(我 PRON/喜歡 VERB/咖啡 NOUN),多字元的詞可以是單一 token。投影片 39:三種語言的「我喜歡咖啡」都是 nsubj/root/obj,head IDs 都是 2 / 0 / 2。
模型錯誤與否定
- 日文「政府は医療従事者を支援する。」:政府(NOUN, nsubj → 6)、医療(compound → 4)、従事者(obj → 6)、支援(VERB, root)、する(AUX)。
- 繁體中文「政府支持醫療工作者。」:模型錯誤——
支持被標成 NOUN,者(PART)被預測為 root。投影片的提醒:詮釋這些輸出之前,先讀原句。 - 否定「政府不支持刪減醫療預算。」:
不(ADV)以 advmod 連到支持(ID 3)。只保留 NOUN 與 VERB 會移除「不」,特徵清單就失去了否定。(在上面的檢視器選這一句,取消勾選 ADV 試試。)
從泰文句法到研究量測
靜態版:POS 標出詞類,依存關係把主詞連到述語與對象 → 把主詞連到「like」與它的受詞,並確認陳述是肯定句 → 這個例子:咖啡的正面偏好 = 1 → 研究問題:哪些對象得到更多正面偏好的表達?語料層次的量測:提到某對象的文件中,表達正面偏好的比例。箭頭由 head 指向 dependent。 這也呼應第 01 章投影片 4 的「咖啡偏好」研究設計。
UDPipe 標註變成 quanteda tokens 與 DFM
# Assume ann_multi contains an annotation table.
a <- subset(ann_multi, upos != "PUNCT")
a <- a[order(a$doc_id, a$sentence_id,
as.integer(a$token_id)), ]
ja_tokens <- split(a$token[a$doc_id == "ja_01"],
a$doc_id[a$doc_id == "ja_01"])
ja_dfm <- dfm(as.tokens(ja_tokens), tolower = FALSE)用 as.tokens() 保留既有的斷詞;中文 DFM 也用同樣方式建。
A:workers (NOUN) / support (VERB) / reform (NOUN);B:workers (NOUN) / oppose (VERB) / reform (NOUN)。POS 是投影片標的示意標籤。
列=文件;欄=你選的特徵;格=計數。名詞過濾會失去立場的對比;字典計數仍需要驗證。
自我檢查
建 DFM、看字頻與文件頻率、TF-IDF、回到上下文
DFM 是之後所有方法(字典、分類、主題模型、縮放)的共同輸入。本章的數字都可以手算驗證。
建立並檢查 DFM
dim(x) topfeatures(x, 6) featnames(x)
> dim(x)
[1] 4 9
> topfeatures(x, 6)
health workers services government supports policy
3 2 2 2 2 2
> featnames(x)
[1] "health" "workers" "need" "services" "government"
[6] "supports" "not" "support" "policy" 4 份文件 × 9 個特徵;最常見的是 health 3、workers 2、services 2、government 2、supports 2、policy 2。列保留文件 ID;完整 DFM 包含第 06 章那 5 欄以外的特徵(need、supports、support、services)。
9 個特徵裡 supports(d2、d4)與 support(d3)是兩個不同的特徵。如果要合併,得靠 stemming、lemmatization 或明確替換(第 06 章投影片 34)——而每種方法都有代價。
term frequency 與 document frequency
colSums(x)[c("health", "workers", "not")]
docfreq(x)[c("health", "workers", "not")]
x_trim <- dfm_trim(x, min_docfreq = 2,
docfreq_type = "count")
featnames(x_trim)> colSums(x)[c("health", "workers", "not")]
health workers not
3 2 1
> docfreq(x)[c("health", "workers", "not")]
health workers not
2 2 1
> x_trim <- dfm_trim(x, min_docfreq = 2,
+ docfreq_type = "count")
> featnames(x_trim)
[1] "health" "workers" "services" "government" "supports"
[6] "policy" | 特徵 | 總出現次數 | 包含它的文件數 |
|---|---|---|
| health | 3 | 2 |
| workers | 2 | 2 |
| not | 1 | 1 |
min_docfreq = 2 這個門檻會移除 not。罕見特徵仍可能承載關鍵意義。 本機輸出(上方 featnames(x_trim))顯示修剪後剩 6 個特徵:health、workers、services、government、supports、policy;df = 1 的 need、not、support 被刪掉——連 support(d3 唯一的動詞)也一起消失。
計數、二元指標與 TF-IDF
| 表示 | 格子的意思 | 可能用途 |
|---|---|---|
| Count | 出現次數 | 以頻率為基礎的量測 |
| Binary | 特徵是否出現 | 以「有沒有出現」比較 |
| TF-IDF | 依語料中的普遍程度調整後的計數 | 文件檢索或比較 |
選擇會改變「重複出現的字」貢獻多少。模型的要求可能限制哪一種表示適合。
把 TF-IDF 公式寫清楚
本課使用原始計數與以 10 為底的對數:
TF-IDF(d, t) = count(d, t) × log10(N / df(t))
- N 是參考語料的文件數;df(t) 是包含特徵 t 的文件數。
- 出現在每一份文件的特徵,在這個公式下 IDF = 0。
- 不同的正規化與平滑規則會產生不同的權重。
x_weighted <- dfm_tfidf(x, scheme_tf = "count",
scheme_df = "inverse", base = 10)
round(as.matrix(x_weighted[, "health"]), 4)
round(as.matrix(x_weighted), 4)> x_weighted <- dfm_tfidf(x, scheme_tf = "count",
+ scheme_df = "inverse", base = 10)
> round(as.matrix(x_weighted[, "health"]), 4)
features
docs health
d1 0.6021
d2 0.3010
d3 0.0000
d4 0.0000
> round(as.matrix(x_weighted), 4)
features
docs health workers need services government supports not support policy
d1 0.6021 0.301 0.6021 0.301 0.000 0.000 0.0000 0.0000 0.000
d2 0.3010 0.000 0.0000 0.301 0.301 0.301 0.0000 0.0000 0.000
d3 0.0000 0.301 0.0000 0.000 0.000 0.000 0.6021 0.6021 0.301
d4 0.0000 0.000 0.0000 0.000 0.301 0.301 0.0000 0.0000 0.301health:N = 4、df = 2,所以 IDF = log10(2) ≈ 0.3010;d1 計數 2 → 0.6021,d2 計數 1 → 0.3010,d3、d4 為 0。本機 R 與投影片 50 完全一致。
互動:TF-IDF 計算機
選一個特徵,看 N、df、IDF 與每份文件的權重。你也可以把第 5 份文件加進參考語料,看看 N 改變後同一個字的權重怎麼變(第 5 份文件是補充,非講義內容)。
用 KWIC 檢查上下文
kwic(toks, pattern = "support*", window = 3)
> kwic(toks, pattern = "support*", window = 3)
Keyword-in-context with 3 matches.
[d2, 3] the government | supports | health services
[d3, 4] workers do not | support | the policy
[d4, 3] the government | supports | the policy 三筆符合:d2「the government supports health services」、d3「workers do not support the policy」、d4「the government supports the policy」。在把一個字的計數當成「支持某政策」的證據之前,先讀它周圍的字——d3 的 support 前面就是 not。
注意:KWIC 用的是 toks(還沒移除停用字的 tokens),所以看得到 not 與 the。pattern "support*" 是 glob 萬用字元,比到 support 與 supports。
自我檢查
dfm_trim(x, min_docfreq = 2, docfreq_type = "count") 會刪掉 not,因為?DFM 拿來做什麼?以及:結果對前處理有多敏感?
同一張 DFM 可以接到很多方法,但每個方法對輸入有不同要求:Wordfish 與主題模型要計數,分類要訓練標籤,Wordscores 要參考分數,相似度可以用 TF-IDF。
小結:DFM、KWIC、TF-IDF
| 工具 | 讓你做什麼 |
|---|---|
| DFM | 表示文件特徵,用於比較與建模 |
| KWIC | 在上下文中讀字,檢查特徵計數的意義 |
| TF-IDF | 強調有區辨力的字,用於檢索與相似度 |
Wordfish 是把文本放到一條維度上的非監督方法:字數 DFM → Wordfish → 文件的相對位置。用途:比較政黨宣言或演說。輸入是計數,不是 TF-IDF 權重。在稱它為「意識形態」之前,要先詮釋並驗證這條量尺。
DFM 的研究應用
| 研究目標 | 方法 | 輸出 |
|---|---|---|
| 估計位置 | Wordfish/Wordscores | 文件的相對位置 |
| 預測類別 | 監督式分類器 | 議題或立場標籤 |
| 研究議題注意力 | LDA/STM/keyATM | 主題與主題比例 |
| 量測一個概念 | 字典 | 類別計數或比例 |
| 比較文件 | 餘弦相似度/分群 | 相似度或文件群 |
輸入很重要:Wordfish 與這些主題模型用計數;分類需要訓練標籤;Wordscores 需要參考分數;相似度可以用 TF-IDF。 這些方法分別在 W4(字典)、W7(縮放)、W8(主題模型)等週深入。
互動:方法配對
每一題選一個方法;答完會顯示這個方法需要的輸入(計數、標籤、參考分數或 TF-IDF)。情境是本教材自擬(補充)。
投影片介紹的應用研究
| 類別 | 研究 | 投影片上的一句話 |
|---|---|---|
| 主題模型 | STM:Roberts et al. (2014) | 比較不同受訪者群體在問卷回答中的主題。 |
| 主題模型 | keyATM:Eshima et al. (2024) | 用選定的關鍵字引導主題,研究政策注意力。 |
| 文本縮放 | Wordfish:Slapin & Proksch (2008) | 從政黨宣言的字數估計政黨相對位置。語料:五個政黨、五次選舉(1990–2005)共 25 份德國政黨宣言;發現:綠黨隨時間往中間移動;讀軸:較高的值代表左,正負號是慣例(Figure 1A, p. 714)。 |
| 文本縮放 | Wordscores:Lowe (2008);Laver et al. (2003) | 用已知分數的參考文本定位新文本。愛爾蘭信任案辯論:3 篇參考演說(+1/−1)→ 為其他 55 篇演說評分,分數越高越支持政府(Laver et al. 2003, Figure 3, p. 328)。 |
| TF-IDF | 文本相似度:Blumenau (2021) | 追蹤後來的發言者在下議院辯論中使用了誰的語言。 |
| TF-IDF | 立場分類:Bestvater & Monroe (2023) | 用 TF-IDF 加 SVM 分類政治上的支持或反對。 |
TF-IDF 提供加權後的特徵;分析決定我們量到什麼。 這些論文的全文不在課程 repo 裡,本教材只轉述投影片上的內容(見第 13 章)。
對前處理的敏感度
| 比較 | 檢查 | 解釋 |
|---|---|---|
| 有/沒有停用字 | 否定與語法脈絡 | 哪些區分消失了? |
| unigram/片語 | 複合概念 | 哪些比對結果改變了? |
| 完整/修剪後的詞彙 | 被刪掉的特徵與空白列 | 哪些文件失去了證據? |
| 計數/TF-IDF | 特徵的相對貢獻 | 結果是否取決於加權? |
比較某一條規則時,固定語料與研究問題不變。 第 06 章的「前處理開關實驗室」與第 11 章的「修剪門檻」「keyness 探索器」都可以拿來實際做這四種比較。
自我檢查
Lab 第 1–2 節:字串、regex、清理議程標籤、建立 corpus
以下程式碼來自 W2/lab/answers/Lab_Session_W2_Answers.R(範例部分與學生版 Lab_Session_W2.R 相同),輸出是本機實際執行的結果(R 4.5.3、quanteda 4.5.1、quanteda.textstats 0.97.2、quanteda.textplots 0.96.1、stringr 1.6.0、dplyr 1.2.1、ggplot2 4.0.3;Linux aarch64)。
課堂設定:安裝、開啟、執行
- 下載並安裝:R 與 Python 3,再安裝 RStudio Desktop 與 Positron。
- 試試 console:R 輸入
1 + 1;Python 輸入print(1 + 1),兩者都回傳 2。 - 在
lab/開啟Lab_Session_W2.R,在 R console 安裝套件(只需一次):
install.packages(c("dplyr", "stringr", "ggplot2",
"quanteda", "quanteda.textstats", "quanteda.textplots"))把工作目錄設成 W2/lab/,Data/ 資料夾放在腳本旁邊。帶回家的技能:在 RStudio 或 Positron 開一個 .R 檔,自己跑完 Lab。 Lab 不計分、不用繳交;不需要 Python、語言模型或 API。
# First use only: uncomment these lines to install the packages.
# install.packages(c("dplyr", "stringr", "ggplot2", "quanteda",
# "quanteda.textstats", "quanteda.textplots"))
library(dplyr)
library(stringr)
library(ggplot2)
library(quanteda)
library(quanteda.textstats)
library(quanteda.textplots)> # First use only: uncomment these lines to install the packages.
> # install.packages(c("dplyr", "stringr", "ggplot2", "quanteda",
> # "quanteda.textstats", "quanteda.textplots"))
> library(dplyr)
Attaching package: ‘dplyr’
The following objects are masked from ‘package:stats’:
filter, lag
The following objects are masked from ‘package:base’:
intersect, setdiff, setequal, union
> library(stringr)
> library(ggplot2)
> library(quanteda)
> library(quanteda.textstats)
> library(quanteda.textplots)載入 dplyr 時出現的 “masked” 訊息是正常的:dplyr 的 filter() 蓋過了 stats 的同名函式。(老師的 HTML 用 message: false 隱藏了這些訊息。)
本機輸出與老師答案 HTML 的對照
我們把本機輸出與 answers/Lab_Session_W2_Answers.html 中老師的輸出逐段比對(空白正規化後;比對紀錄在 tad/labs/W2/compare_with_instructor_html.txt):
- 所有數字與表格內容都一致:5000、271、81、364、368、2995、279、23 × 30640、23 × 5474、23 × 3424、所有搭配詞的 λ 與 z、所有 keyness 的 χ²。
- 唯一的文字差異:
summary()的標題,本機(quanteda 4.5.1)印 “corpus of 5,000 documents”,老師的 HTML 印 “Corpus consisting of 5000 documents”。這是套件版本的列印格式差異,內容相同。 - 投影片本身沒有 Lab 的數字(只有 5,000 筆與 1945–2025),所以沒有需要並列說明的不一致。
讀資料、建立 year 變數
# Find the supplied data. If asked, choose the .rds file in W2/lab/Data.
paths <- c("W2/lab/Data/hc_sample_1945_2025.rds",
"lab/Data/hc_sample_1945_2025.rds",
"../Data/hc_sample_1945_2025.rds",
"Data/hc_sample_1945_2025.rds")
found <- paths[file.exists(paths)]
if (length(found) == 0) found <- file.choose()
data_path <- normalizePath(found[1])
setwd(dirname(dirname(data_path)))
hoc <- readRDS(data_path)
nrow(hoc)> # Find the supplied data. If asked, choose the .rds file in W2/lab/Data.
> paths <- c("W2/lab/Data/hc_sample_1945_2025.rds",
+ "lab/Data/hc_sample_1945_2025.rds",
+ "../Data/hc_sample_1945_2025.rds",
+ "Data/hc_sample_1945_2025.rds")
> found <- paths[file.exists(paths)]
> if (length(found) == 0) found <- file.choose()
> data_path <- normalizePath(found[1])
> setwd(dirname(dirname(data_path)))
> hoc <- readRDS(data_path)
> nrow(hoc)
[1] 5000hoc <- hoc |> mutate(year = as.integer(format(date, "%Y"))) hoc |> select(date, year, speaker, party, agenda, terms) |> head(5)
> hoc <- hoc |>
+ mutate(year = as.integer(format(date, "%Y")))
> hoc |>
+ select(date, year, speaker, party, agenda, terms) |>
+ head(5)
date year speaker party
1 1945-01-16 1945 Mr. Johnstone Liberal
2 1945-01-16 1945 Mr. Woodburn Labour
3 1945-01-24 1945 Mr. Eden Conservative
4 1945-01-30 1945 Vice-Admiral Taylor Conservative
5 1945-01-31 1945 Sir M. Sueter Conservative
agenda terms
1 Export Trade 72
2 Fruit and Vegetables (Short Weight) 53
3 BRITISH PRISONERS OF WAR, FAR EAST 29
4 FIGHTING SERVICES (PAY) 30
5 ROYAL NAVY (GERMAN SUBMARINE WARFARE) 50terms 是每筆發言的詞數(資料提供者算的)。抽樣框排除了很短的發言,但前五筆的 terms 仍只有 29–72。
字串操作:extract、which、locate
agenda_labels <- hoc$agenda[1:8] agenda_labels str(agenda_labels)
> agenda_labels <- hoc$agenda[1:8] > agenda_labels [1] "Export Trade" [2] "Fruit and Vegetables (Short Weight)" [3] "BRITISH PRISONERS OF WAR, FAR EAST" [4] "FIGHTING SERVICES (PAY)" [5] "ROYAL NAVY (GERMAN SUBMARINE WARFARE)" [6] "TOWN AND COUNTRY PLANNING (SCOTLAND) BILL" [7] "WAR GRATUITIES" [8] "WATER BILL" > str(agenda_labels) chr [1:8] "Export Trade" "Fruit and Vegetables (Short Weight)" ...
str_extract(agenda_labels, "Trade") str_extract(agenda_labels, "WAR")
> str_extract(agenda_labels, "Trade") [1] "Trade" NA NA NA NA NA NA NA > str_extract(agenda_labels, "WAR") [1] NA NA "WAR" NA "WAR" NA "WAR" NA
str_extract(agenda_labels, "war") str_extract(str_to_lower(agenda_labels), "war")
> str_extract(agenda_labels, "war") [1] NA NA NA NA NA NA NA NA > str_extract(str_to_lower(agenda_labels), "war") [1] NA NA "war" NA "war" NA "war" NA
NA代表那個標籤裡找不到 pattern,不是整份文件缺失。- pattern 預設區分大小寫:
"war"在原始標籤裡一個都比不到;先str_to_lower()後,第 3、5、7 個標籤都比到了。 - 注意第 5 個是 “ROYAL NAVY (GERMAN SUBMARINE WARFARE)”——比到的是 warfare 的一部分。下一段的字界(word boundary)就是處理這件事。
str_which(str_to_lower(agenda_labels), "war") str_which(str_to_lower(agenda_labels), "trade")
> str_which(str_to_lower(agenda_labels), "war") [1] 3 5 7 > str_which(str_to_lower(agenda_labels), "trade") [1] 1
str_locate(str_to_lower(agenda_labels), "war")
> str_locate(str_to_lower(agenda_labels), "war")
start end
[1,] NA NA
[2,] NA NA
[3,] 22 24
[4,] NA NA
[5,] 30 32
[6,] NA NA
[7,] 1 3
[8,] NA NAstr_which() 回傳位置(3、5、7;trade 只在 1);str_locate() 回傳第一個符合的起訖字元位置(例如第 7 個標籤 “war gratuities” 的 1–3)。str_locate_all() 回傳每一個符合(輸出很長,見完整 run_output.txt)。
正規表示式與字界
speech_urls <- hoc$speech_url[1:5] speech_urls
> speech_urls <- hoc$speech_url[1:5] > speech_urls [1] "https://api.parliament.uk/historic-hansard/written_answers/1945/jan/16/export-trade#S5CV0407P0_19450116_CWA_118" [2] "https://api.parliament.uk/historic-hansard/commons/1945/jan/16/fruit-and-vegetables-short-weight#S5CV0407P0_19450116_HOC_181" [3] "https://api.parliament.uk/historic-hansard/written_answers/1945/jan/24/british-prisoners-of-war-far-east#S5CV0407P0_19450124_CWA_14" [4] "https://api.parliament.uk/historic-hansard/commons/1945/jan/30/fighting-services-pay#S5CV0407P0_19450130_HOC_309" [5] "https://api.parliament.uk/historic-hansard/written_answers/1945/jan/31/royal-navy-german-submarine-warfare#S5CV0407P0_19450131_CWA_91"
str_extract(speech_urls, "\\d") str_extract(speech_urls, "\\d+") str_extract_all(speech_urls, "\\d+")
> str_extract(speech_urls, "\\d") [1] "1" "1" "1" "1" "1" > str_extract(speech_urls, "\\d+") [1] "1945" "1945" "1945" "1945" "1945" > str_extract_all(speech_urls, "\\d+") [[1]] [1] "1945" "16" "5" "0407" "0" "19450116" "118" [[2]] [1] "1945" "16" "5" "0407" "0" "19450116" "181" [[3]] [1] "1945" "24" "5" "0407" "0" "19450124" "14" [[4]] [1] "1945" "30" "5" "0407" "0" "19450130" "309" [[5]] [1] "1945" "31" "5" "0407" "0" "19450131" "91"
str_extract(speech_urls, "\\d{4}/[a-z]{3}/\\d{2}")> str_extract(speech_urls, "\\d{4}/[a-z]{3}/\\d{2}")
[1] "1945/jan/16" "1945/jan/16" "1945/jan/24" "1945/jan/30" "1945/jan/31"example_text <- c( "The war changed British politics.", "The committee moved towards a compromise.", "Post-war trade was discussed." ) str_detect(str_to_lower(example_text), "war") str_detect(str_to_lower(example_text), "\\bwar\\b")
> example_text <- c( + "The war changed British politics.", + "The committee moved towards a compromise.", + "Post-war trade was discussed." + ) > str_detect(str_to_lower(example_text), "war") [1] TRUE TRUE TRUE > str_detect(str_to_lower(example_text), "\\bwar\\b") [1] TRUE FALSE TRUE
寬鬆的 pattern 三句都比到;\\bwar\\b 排除了 towards,但仍比到 post-war,因為連字號被當成字界。選符合你想要意義的規則。(Lab 說明)
str_replace(agenda_labels, "Trade", "TRADE") str_replace_all(agenda_labels, "[aeiou]", "-")
> str_replace(agenda_labels, "Trade", "TRADE") [1] "Export TRADE" [2] "Fruit and Vegetables (Short Weight)" [3] "BRITISH PRISONERS OF WAR, FAR EAST" [4] "FIGHTING SERVICES (PAY)" [5] "ROYAL NAVY (GERMAN SUBMARINE WARFARE)" [6] "TOWN AND COUNTRY PLANNING (SCOTLAND) BILL" [7] "WAR GRATUITIES" [8] "WATER BILL" > str_replace_all(agenda_labels, "[aeiou]", "-") [1] "Exp-rt Tr-d-" [2] "Fr--t -nd V-g-t-bl-s (Sh-rt W--ght)" [3] "BRITISH PRISONERS OF WAR, FAR EAST" [4] "FIGHTING SERVICES (PAY)" [5] "ROYAL NAVY (GERMAN SUBMARINE WARFARE)" [6] "TOWN AND COUNTRY PLANNING (SCOTLAND) BILL" [7] "WAR GRATUITIES" [8] "WATER BILL"
清理議程標籤
hoc |> filter(str_detect(str_to_lower(agenda), "business of the house")) |> count(agenda, sort = TRUE) |> head(10)
> hoc |>
+ filter(str_detect(str_to_lower(agenda), "business of the house")) |>
+ count(agenda, sort = TRUE) |>
+ head(10)
agenda
1 BUSINESS OF THE HOUSE
2 Business of the House
3 Business Of The House
4 BUSINESS OF THE HOUSE (FINANCE BILL)
5 Business Of The House [Defence Policy]
6 Business Of The House [Modernisation Of The House]
7 Business Of The House [Orders Of The Day > Child Support, Pensions And Social Security Bill > New Clause 9]
8 Business Of The House [Orders Of The Day > Security Service Bill]
9 Business Of The House [Orders Of The Day]
10 Business Of The House [Prayers > Bills Presented]
n
1 56
2 54
3 34
4 1
5 1
6 1
7 1
8 1
9 1
10 1同一個議程 “Business of the House” 至少有三種大小寫寫法(56+54+34 筆),還有一堆帶中括號脈絡的變體。
hoc <- hoc |>
mutate(
agenda_clean = agenda |>
str_to_lower() |>
str_squish() |>
str_replace_all("\\s*\\[.*\\]", ""),
agenda_clean = case_when(
agenda_clean == "business of the house" ~ "Business of the House",
agenda_clean == "points of order" ~ "Points of Order",
agenda_clean == "topical questions" ~ "Topical Questions",
str_detect(agenda_clean, "^engagements") ~ "Engagements",
TRUE ~ str_to_title(agenda_clean)
)
)
hoc |>
count(agenda_clean, sort = TRUE) |>
head(15)> hoc <- hoc |>
+ mutate(
+ agenda_clean = agenda |>
+ str_to_lower() |>
+ str_squish() |>
+ str_replace_all("\\s*\\[.*\\]", ""),
+ agenda_clean = case_when(
+ agenda_clean == "business of the house" ~ "Business of the House",
+ agenda_clean == "points of order" ~ "Points of Order",
+ agenda_clean == "topical questions" ~ "Topical Questions",
+ str_detect(agenda_clean, "^engagements") ~ "Engagements",
+ TRUE ~ str_to_title(agenda_clean)
+ )
+ )
> hoc |>
+ count(agenda_clean, sort = TRUE) |>
+ head(15)
agenda_clean n
1 <NA> 206
2 Business of the House 151
3 Engagements 81
4 Topical Questions 69
5 Finance Bill 18
6 Points of Order 15
7 European Economic Community 14
8 Debate On The Address 12
9 Budget Resolutions And Economic Situation 11
10 Northern Ireland 11
11 European Council 9
12 Housing 9
13 Local Government Finance 9
14 National Health Service 9
15 Amendment Of The Law 8把所有以 Engagements 開頭的標籤合併,對描述性的圖可能有幫助,但也移除了細節。清理選擇要記錄下來。另外注意輸出第一列:206 筆 agenda 是 NA,清理不會替它們補上任何東西。
互動:議程清理管線(真實 5,000 筆)
資料:R 匯出的 hoc$agenda(4,083 個不同的非 NA 標籤+206 筆 NA)。一次開關一個步驟,看前 15 名與「不同標籤數」怎麼變。全部開啟 = Lab 的 clean_agenda_labels,前 15 名應與上方 R 輸出一致(下方會自動比對)。str_to_title() 在 JS 是近似實作。
建立並檢查 corpus
hoc_corpus <- corpus( hoc, text_field = "text" )
summary(hoc_corpus, n = 10)
> summary(hoc_corpus, n = 10)
corpus of 5,000 documents, showing 10 documents:
Text Types Tokens Sentences date
text1 53 76 2 1945-01-16
text2 40 55 1 1945-01-16
text3 26 30 1 1945-01-24
text4 30 35 3 1945-01-30
text5 43 54 1 1945-01-31
text6 236 529 16 1945-02-14
text7 81 132 3 1945-02-20
text8 43 52 1 1945-02-21
text9 26 32 1 1945-02-22
text10 58 78 3 1945-02-23
agenda speechnumber speaker
Export Trade 1164121 Mr. Johnstone
Fruit and Vegetables (Short Weight) 1164131 Mr. Woodburn
BRITISH PRISONERS OF WAR, FAR EAST 1166439 Mr. Eden
FIGHTING SERVICES (PAY) 1167553 Vice-Admiral Taylor
ROYAL NAVY (GERMAN SUBMARINE WARFARE) 1168346 Sir M. Sueter
TOWN AND COUNTRY PLANNING (SCOTLAND) BILL 1171770 Mr. Johnston
WAR GRATUITIES 1172870 Sir J. Anderson
WATER BILL 1173225 Major Mills
Committee of Inquiry 1173549 Mr. Viant
MINISTRY OF FUEL AND POWER BILL 1173930 Earl Winterton
party party.facts.id chair terms
Liberal NA FALSE 72
Labour NA FALSE 53
Conservative NA FALSE 29
Conservative NA FALSE 30
Conservative NA FALSE 50
Labour NA FALSE 489
National NA FALSE 116
Conservative NA FALSE 49
Labour NA FALSE 31
Conservative NA FALSE 64
speech_url
https://api.parliament.uk/historic-hansard/written_answers/1945/jan/16/export-trade#S5CV0407P0_19450116_CWA_118
https://api.parliament.uk/historic-hansard/commons/1945/jan/16/fruit-and-vegetables-short-weight#S5CV0407P0_19450116_HOC_181
https://api.parliament.uk/historic-hansard/written_answers/1945/jan/24/british-prisoners-of-war-far-east#S5CV0407P0_19450124_CWA_14
https://api.parliament.uk/historic-hansard/commons/1945/jan/30/fighting-services-pay#S5CV0407P0_19450130_HOC_309
https://api.parliament.uk/historic-hansard/written_answers/1945/jan/31/royal-navy-german-submarine-warfare#S5CV0407P0_19450131_CWA_91
https://api.parliament.uk/historic-hansard/commons/1945/feb/14/town-and-country-planning-scotland-bill#S5CV0408P0_19450214_HOC_306
https://api.parliament.uk/historic-hansard/commons/1945/feb/20/war-gratuities#S5CV0408P0_19450220_HOC_225
https://api.parliament.uk/historic-hansard/commons/1945/feb/21/water-bill#S5CV0408P0_19450221_HOC_266
https://api.parliament.uk/historic-hansard/commons/1945/feb/22/committee-of-inquiry#S5CV0408P0_19450222_HOC_119
https://api.parliament.uk/historic-hansard/commons/1945/feb/23/ministry-of-fuel-and-power-bill#S5CV0408P0_19450223_HOC_69
parliament iso3country party_raw year
UK-HouseOfCommons GBR Liberal 1945
UK-HouseOfCommons GBR Labour 1945
UK-HouseOfCommons GBR Conservative 1945
UK-HouseOfCommons GBR Conservative 1945
UK-HouseOfCommons GBR Conservative 1945
UK-HouseOfCommons GBR Labour 1945
UK-HouseOfCommons GBR National 1945
UK-HouseOfCommons GBR Conservative 1945
UK-HouseOfCommons GBR Labour 1945
UK-HouseOfCommons GBR Conservative 1945
agenda_clean
Export Trade
Fruit And Vegetables (Short Weight)
British Prisoners Of War, Far East
Fighting Services (Pay)
Royal Navy (German Submarine Warfare)
Town And Country Planning (Scotland) Bill
War Gratuities
Water Bill
Committee Of Inquiry
Ministry Of Fuel And Power Billsummary 的 Types/Tokens/Sentences 是 quanteda 即時算的(含標點);例如 text6 有 529 個 tokens、16 個句子。這和資料裡的 terms 欄(489)定義不同。
ndoc(hoc_corpus)
> ndoc(hoc_corpus) [1] 5000
還是 5,000 份文件:建 corpus 只是改變儲存方式,不會選擇或分類發言。(Lab 說明)
names(docvars(hoc_corpus)) head(docvars(hoc_corpus, "party"), 10) head(docvars(hoc_corpus, "agenda_clean"), 10)
> names(docvars(hoc_corpus)) [1] "date" "agenda" "speechnumber" "speaker" [5] "party" "party.facts.id" "chair" "terms" [9] "speech_url" "parliament" "iso3country" "party_raw" [13] "year" "agenda_clean" > head(docvars(hoc_corpus, "party"), 10) [1] "Liberal" "Labour" "Conservative" "Conservative" "Conservative" [6] "Labour" "National" "Conservative" "Labour" "Conservative" > head(docvars(hoc_corpus, "agenda_clean"), 10) [1] "Export Trade" [2] "Fruit And Vegetables (Short Weight)" [3] "British Prisoners Of War, Far East" [4] "Fighting Services (Pay)" [5] "Royal Navy (German Submarine Warfare)" [6] "Town And Country Planning (Scotland) Bill" [7] "War Gratuities" [8] "Water Bill" [9] "Committee Of Inquiry" [10] "Ministry Of Fuel And Power Bill"
as.character(hoc_corpus)[1]
> as.character(hoc_corpus)[1] text1 "In addition to discussions with a large number of individual merchants and merchant bankers, many meetings connected with our post-war trade have taken place between my Department and Export Groups, a number of which include merchants among their members. The Consultative Committee which advised my Department on its future practice and procedure included a merchant among its members, and I have invited a merchant to …〔以下略;完整輸出見 tad/labs/W2/run_output.txt〕
取子集與改變文件單位
labour_since_2010 <- corpus_subset( hoc_corpus, party == "Labour" & year >= 2010 ) ndoc(labour_since_2010) summary(labour_since_2010, n = 5)
> labour_since_2010 <- corpus_subset(
+ hoc_corpus,
+ party == "Labour" & year >= 2010
+ )
> ndoc(labour_since_2010)
[1] 271
> summary(labour_since_2010, n = 5)
corpus of 271 documents, showing 5 documents:
Text Types Tokens Sentences date
text4015 77 131 7 2010-01-12
text4017 98 163 6 2010-01-28
text4019 93 137 7 2010-02-10
text4021 53 73 3 2010-02-25
text4022 181 345 13 2010-03-03
agenda
NHS Funding [Oral Answers to Questions > Oral Answers to Questions > Health > Health]
UK Arrest Warrants (Alleged War Crimes)
Armed Forces Compensation Scheme
Topical Questions [Oral Answers to Questions > Energy and Climate Change]
Communications Allowance
speechnumber speaker party party.facts.id chair terms speech_url
81 Mike O'Brien Labour 1516 FALSE 123 <NA>
377 Barry Gardiner Labour 1516 FALSE 146 <NA>
193 Bob Ainsworth Labour 1516 FALSE 126 <NA>
117 Jim McGovern Labour 1516 FALSE 68 <NA>
293 Keith Hill Labour 1516 FALSE 301 <NA>
parliament iso3country party_raw year
UK-HouseOfCommons GBR Lab 2010
UK-HouseOfCommons GBR Lab 2010
UK-HouseOfCommons GBR Lab 2010
UK-HouseOfCommons GBR Lab 2010
UK-HouseOfCommons GBR Lab 2010
agenda_clean
Nhs Funding
Uk Arrest Warrants (Alleged War Crimes)
Armed Forces Compensation Scheme
Topical Questions
Communications Allowance271 篇 2010 年起的 Labour 發言;hoc_corpus 仍是完整的 5,000 篇。
engagements_corpus <- corpus_subset( hoc_corpus, agenda_clean == "Engagements" ) ndoc(engagements_corpus) summary(engagements_corpus, n = 5)
> engagements_corpus <- corpus_subset(
+ hoc_corpus,
+ agenda_clean == "Engagements"
+ )
> ndoc(engagements_corpus)
[1] 81
> summary(engagements_corpus, n = 5)
corpus of 81 documents, showing 5 documents:
Text Types Tokens Sentences date agenda speechnumber
text2238 91 153 7 1981-03-05 Engagements 155289
text2303 30 35 2 1982-04-06 Engagements 279256
text2350 92 151 10 1983-01-27 Engagements 369787
text2390 44 51 1 1983-11-03 Engagements 439481
text2424 31 53 1 1984-03-20 Engagements 505077
speaker party party.facts.id chair terms
The Prime Minister Conservative NA FALSE 139
The Prime Minister Conservative NA FALSE 33
The Prime Minister Conservative NA FALSE 130
Mr. Steel Liberal NA FALSE 49
Mr. Dobson Labour NA FALSE 48
speech_url
https://api.parliament.uk/historic-hansard/commons/1981/mar/05/engagements#S5CV1000P0_19810305_HOC_140
https://api.parliament.uk/historic-hansard/written_answers/1982/apr/06/engagements#S6CV0021P0_19820406_CWA_91
https://api.parliament.uk/historic-hansard/commons/1983/jan/27/engagements#S6CV0035P0_19830127_HOC_125
https://api.parliament.uk/historic-hansard/commons/1983/nov/03/engagements#S6CV0047P0_19831103_HOC_153
https://api.parliament.uk/historic-hansard/commons/1984/mar/20/engagements#S6CV0056P0_19840320_HOC_154
parliament iso3country party_raw year agenda_clean
UK-HouseOfCommons GBR Conservative Party 1981 Engagements
UK-HouseOfCommons GBR Conservative Party 1982 Engagements
UK-HouseOfCommons GBR Conservative Party 1983 Engagements
UK-HouseOfCommons GBR Liberal Party 1983 Engagements
UK-HouseOfCommons GBR Labour Party 1984 Engagementsengagements_sentences <- corpus_reshape( engagements_corpus, to = "sentences" ) ndoc(engagements_corpus) ndoc(engagements_sentences)
> engagements_sentences <- corpus_reshape( + engagements_corpus, + to = "sentences" + ) > ndoc(engagements_corpus) [1] 81 > ndoc(engagements_sentences) [1] 364
81 篇發言 → 364 個句子文件。每個句子現在都被當成一份文件——這是一個重大的研究設計選擇,改變分析單位可能改變結論。(Lab 說明;投影片 6)
as.character(engagements_sentences)[1:5]
> as.character(engagements_sentences)[1:5]
text2238.1
"With regard to the right hon."
text2238.2
"Gentleman's question on Northern Ireland, I shall, of course, be repeating and emphasising my personal commitment to the guarantee to the people of Northern Ireland, which is enshrined in law in this country."
text2238.3
"With regard to what the right hon."
text2238.4
"Gentleman said about pensioners, I usually see delegations of pensioners in my own constituency."
text2238.5
"I stress that the Government have kept 413 the pension slightly ahead of the rise in the cost of living, and our first increase actually provided an additional amount to make up for the shortfall of the previous Government." - text2238.1 只有 “With regard to the right hon.”,下一句從 “Gentleman's question…” 開始:
hon.的句點是縮寫,不是句尾。Lab 的提醒正是這個。 - text2238.5 裡有 “the Government have kept 413 the pension”:這個 413 看起來是 Hansard 的欄位編號混進了正文(本教材的觀察,非講義內容)——第 03 章說的「記錄慣例」,它會變成一個數字 token。
R 執行清單
自我檢查
str_extract(agenda_labels, "war") 全部回傳 NA,但先 str_to_lower() 就比到 3 個。原因是?corpus_reshape(engagements_corpus, to = "sentences") 把 81 份文件變成 364 份。下列哪個說法錯誤?agenda_clean 的第一名是 <NA>(206 筆)。這代表?agenda 的次數表第一列就是 NA 206(練習 7 的輸出)。Lab 第 3–4 節:tokens、片語、KWIC、搭配詞、DFM、keyness、時間趨勢
Lab 建了兩份 tokens:一份保留原貌給 KWIC 讀上下文,另一份轉小寫、去停用字給 DFM 計數。這正是投影片 14 說的「分支」。
切字與合併多字詞
hoc_tokens <- tokens( hoc_corpus, remove_punct = TRUE, remove_symbols = TRUE, remove_numbers = FALSE )
hoc_tokens <- tokens_compound(
hoc_tokens,
pattern = phrase(c(
"Prime Minister",
"House of Commons",
"European Union",
"National Health Service"
))
)這份 hoc_tokens 保留大小寫與停用字(只移除標點與符號),所以 KWIC 讀起來像原文。
KWIC:在上下文中讀字
kwic(
hoc_tokens,
pattern = phrase("European_Union"),
window = 8
) |>
head(10)> kwic(
+ hoc_tokens,
+ pattern = phrase("European_Union"),
+ window = 8
+ ) |>
+ head(10)
Keyword-in-context with 10 matches.
[text1971, 121] Hull Central Mr McNamara is at the Western |
[text2832, 297] CSCE context beyond that available in the Western |
[text2984, 155] Chancellor Kohl to impose their blueprint of a |
[text3048, 41] is that he wishes Britain to leave the |
[text3058, 23] proposal under title VI of the treaty on |
[text3103, 34] a significant loosening in our relations with the |
[text3103, 63] right to trade with the countries in the |
[text3144, 28] not to contributions by national Governments to the |
[text3257, 760] of our continued and deepening membership of the |
[text3356, 15] in Berlin demonstrated by the fact that the |
European_Union | in Paris It is all very well making
European_Union | His points were echoed to some extent by
European_union | on Europe before it realises what has happened
European_Union | Is that what he is saying
European_Union | to combat serious fraud against the Community budget
European_Union | We hope that we will be able to
European_Union | The hill farmers in my hon Friend's constituency
European_Union | but to money spent by national Governments on
European_Union | We have heard much about national sovereignty What
European_Union | development budget for the next seven years was kwic( hoc_tokens, pattern = "economy", window = 8, valuetype = "fixed", case_insensitive = TRUE ) |> head(10)
> kwic(
+ hoc_tokens,
+ pattern = "economy",
+ window = 8,
+ valuetype = "fixed",
+ case_insensitive = TRUE
+ ) |>
+ head(10)
Keyword-in-context with 10 matches.
[text96, 980] a quadripartite agreement to the administration of the |
[text105, 209] must be a major thing in our national |
[text147, 318] serious matters of the readjustment of our national |
[text405, 305] considered would be absorbed in the normal peace-time |
[text472, 450] there has been a very real practice of |
[text537, 987] time it must have been the result of |
[text539, 629] unless we maintain a firm control upon our |
[text705, 2326] inflation by monetary means which depresses the whole |
[text729, 6] and secondly the efficiency and |
[text737, 390] of the world Oil is vital to our |
economy | of Germany as a single unit there will
economy | from now on As has been pointed out
economy | to peace conditions I see no advantage in
economy | of the countries to which they are exported
economy | in the Royal Household If I may say
economy | in the last Government I can assure hon
economy | inflation and excessive public spending and increased taxation
economy | The Economic Secretary who I understand will reply
economy | of its operation I know the difficulties that
economy | and our Commonwealth should help to provide it 讀每個符合前後的字。單獨一個 economy 的出現,並不告訴你講者對經濟的評價是正面還是負面。(Lab 說明)例如 text472「a very real practice of economy in the Royal Household」的 economy 指的是「節約」,不是國民經濟——一字多義正是投影片 30 說的「歧義需要上下文」。另外看 European_Union 的輸出:text1971 與 text2832 的前一個字都是 Western,也就是另一個組織「西歐聯盟」(Western European Union);text2984 則是小寫的 European_union。合併片語之後,仍要用 KWIC 檢查它比到了什麼(本教材的觀察)。
互動:KWIC 探索器(700 篇真實發言樣本)
為了控制檔案大小,這裡內嵌的是從 5,000 篇中以固定種子(20261106)抽出的 700 篇發言,每篇最多前 1,400 個字元(R 匯出)。切字是 JS 的簡化版(以空白與標點切開),結果只用來練習「讀上下文」,數量不等於 R 對全部 5,000 篇的結果。
給 DFM 用的第二份 tokens
hoc_tokens_dfm <- tokens(
hoc_corpus,
what = "word",
remove_punct = TRUE,
padding = TRUE,
remove_symbols = TRUE,
remove_numbers = FALSE,
remove_url = TRUE,
remove_separators = TRUE,
split_hyphens = FALSE
) |>
tokens_tolower() |>
tokens_remove(stopwords("en"), padding = TRUE)搭配詞(collocations)
hoc_collocations <- textstat_collocations( hoc_tokens_dfm, min_count = 10 ) |> arrange(desc(lambda)) head(hoc_collocations, 20)
> hoc_collocations <- textstat_collocations(
+ hoc_tokens_dfm,
+ min_count = 10
+ ) |>
+ arrange(desc(lambda))
> head(hoc_collocations, 20)
collocation count count_nested length lambda z
975 hong kong 15 0 2 18.01655 8.936495
933 sri lanka 23 0 2 15.86775 10.706798
924 per cent 724 0 2 15.86141 11.197966
951 sinn fein 17 0 2 14.58255 10.028858
957 belle isle 12 0 2 14.08785 9.655601
785 sulphur dioxide 10 0 2 13.96352 14.591709
652 ad hoc 12 0 2 13.79410 16.956018
779 slum clearance 11 0 2 13.48395 14.707109
965 antisocial behaviour 18 0 2 13.43125 9.332776
756 sinn fã 15 0 2 13.25436 14.983942
586 saddam hussein 15 0 2 13.11126 17.865491
521 liberal democrats 37 0 2 12.56315 18.846379
410 dispatch box 23 0 2 12.55494 20.710735
13 northern ireland 338 0 2 12.41462 52.601297
821 lifelong learning 11 0 2 12.30193 13.926595
331 mentally handicapped 14 0 2 12.29736 22.174040
100 united kingdom 307 0 2 12.18297 30.368548
507 thames gateway 13 0 2 12.12581 19.071920
385 privy seal 13 0 2 12.11320 21.252571
306 raw materials 18 0 2 12.03436 22.646568lambda(λ)是關聯強度,z是它的標準化值;這裡依 λ 排序。hong kong(λ ≈ 18.02)、sri lanka、per cent(724 次)排最前面。northern ireland出現 338 次,λ ≈ 12.41——投影片 33 的「統計搭配詞候選」例子。sinn fein(17)與sinn fã(15)同時出現:同一個政黨名稱因編碼問題被拆成兩個特徵(第 03 章)。- 高關聯不等於有用:投影片 33 要你先檢查用法,再加進量測規則。
hoc_collocation_phrases <- hoc_collocations |> filter(lambda > 10) |> pull(collocation) |> phrase() hoc_tokens_dfm <- tokens_compound( hoc_tokens_dfm, pattern = hoc_collocation_phrases ) hoc_tokens_dfm <- tokens_remove(hoc_tokens_dfm, "")
把 λ > 10 的搭配詞黏成一個 token,再用 tokens_remove(hoc_tokens_dfm, "") 移除 padding 留下的空字串。
看前 40 個搭配詞(真實 R 輸出)
由 R 匯出:head(hoc_collocations, 40)。
建立政黨層級的 DFM
hoc_dfm_party <- dfm(hoc_tokens_dfm) hoc_dfm_party <- dfm_group( hoc_dfm_party, groups = docvars(hoc_dfm_party, "party") ) dim(hoc_dfm_party)
> hoc_dfm_party <- dfm(hoc_tokens_dfm) > hoc_dfm_party <- dfm_group( + hoc_dfm_party, + groups = docvars(hoc_dfm_party, "party") + ) > dim(hoc_dfm_party) [1] 23 30640
dim() 先列後欄:分組之後,列是 23 個政黨(不是 5,000 篇發言),欄是 30,640 個特徵;格子是該政黨所有發言的加總次數。(Lab 說明)
topfeatures(hoc_dfm_party, 25)
> topfeatures(hoc_dfm_party, 25)
hon government right member can people one
6569 3213 2780 2428 2423 2296 2288
friend minister house made many members time
2279 2049 2000 1600 1537 1515 1503
bill said gentleman may make secretary now
1484 1484 1372 1351 1343 1340 1322
state mr us say
1314 1310 1247 1237 最常見的是 hon(6,569)、government、right、member、friend……很多是議會禮儀用語(“my right hon. Friend”)。W8 的主題模型就另外建了「議會停用字」把它們刪掉——停用字表要看語料。
修剪罕見特徵
hoc_dfm_party_trimmed <- dfm_trim( hoc_dfm_party, min_termfreq = 10 ) dim(hoc_dfm_party) dim(hoc_dfm_party_trimmed)
> hoc_dfm_party_trimmed <- dfm_trim( + hoc_dfm_party, + min_termfreq = 10 + ) > dim(hoc_dfm_party) [1] 23 30640 > dim(hoc_dfm_party_trimmed) [1] 23 5474
30,640 → 5,474 個特徵(min_termfreq = 10:全語料至少出現 10 次)。修剪移除低於門檻的特徵;它不會把剩下的計數變成百分比。修剪不是中性的:罕見字可能是雜訊,也可能很重要。(Lab 說明)
互動:修剪門檻會留下多少特徵?(真實計數)
R 匯出了修剪前 30,640 個特徵的總次數分布。拖動門檻看保留的特徵數與 token 數。門檻 10 應得 5,474(Lab 範例),門檻 20 應得 3,424(練習 10)。
文字雲與頻率圖
set.seed(719102) # keep the layout reproducible textplot_wordcloud(hoc_dfm_party_trimmed, max_words = 50)
textplot_wordcloud(hoc_dfm_party_trimmed, max_words = 50)(set.seed(719102))。點圖放大。文字雲適合快速看一眼,通常不是研究上最好的最終圖。(Lab 說明)
hoc_feature_frequency <- textstat_frequency(
hoc_dfm_party_trimmed,
n = 25
)
hoc_feature_frequency <- hoc_feature_frequency |>
mutate(feature = reorder(feature, frequency))
ggplot(
hoc_feature_frequency,
aes(x = feature, y = frequency)
) +
geom_point() +
coord_flip() +
labs(
x = NULL,
y = "Frequency",
title = "Most frequent features in the party-level DFM"
) +
theme_minimal()用 keyness 比較政黨
conservative_keyness <- textstat_keyness( hoc_dfm_party_trimmed, target = docnames(hoc_dfm_party_trimmed) == "Conservative" ) head(conservative_keyness, 20) textplot_keyness(conservative_keyness, n = 20)
> conservative_keyness <- textstat_keyness(
+ hoc_dfm_party_trimmed,
+ target = docnames(hoc_dfm_party_trimmed) == "Conservative"
+ )
> head(conservative_keyness, 20)
feature chi2 p n_target n_reference
1 hon 59.60149 1.165734e-14 3303 3266
2 friend 55.94153 7.460699e-14 1216 1063
3 aircraft 54.96878 1.224576e-13 116 38
4 cyberstalking 50.16056 1.416645e-12 42 0
5 stalking 42.99415 5.490386e-11 36 0
6 drug 38.84916 4.578508e-10 54 10
7 right 35.99095 1.982363e-09 1424 1356
8 parking 31.82940 1.683252e-08 36 4
9 icmp 29.85626 4.652923e-08 25 0
10 research 28.26946 1.055484e-07 117 62
11 misuse 26.81702 2.236585e-07 25 1
12 air 25.09368 5.461162e-07 110 60
13 badger 24.44132 7.660780e-07 23 1
14 bail 23.87148 1.029863e-06 27 3
15 medicines 23.85041 1.041196e-06 31 5
16 tyne 23.85041 1.041196e-06 31 5
17 training 20.28065 6.687365e-06 125 79
18 badgers 19.10759 1.235523e-05 16 0
19 businesses 18.61571 1.598976e-05 113 71
20 iran 18.51407 1.686546e-05 18 1
> textplot_keyness(conservative_keyness, n = 20)textplot_keyness(conservative_keyness, n = 20)(本機 R 產生)。- keyness 比較「目標組」(Conservative)與「參考組」(其他 22 個政黨合併)的用字。正的 χ² = 在 Conservative 發言中相對過度出現;負的 = 偏向參考組。這是用字的比較,不是情緒分數。(Lab 說明)
- hon(3,303 vs. 3,266)與 friend 排前面:這兩個字主要來自 “my hon. Friend” 這類議會稱呼,可能反映發言角色與議會慣例,而不是議題立場(本教材解讀)。
- cyberstalking(42 vs. 0)、stalking、icmp(25 vs. 0)、badger 這類字只靠少數發言就衝上前面——在 5,000 筆樣本裡,一兩篇長發言就能主導 keyness。讀它們之前,先用 KWIC 看是哪幾篇。
互動:keyness 探索器(真實政黨 DFM)
資料是 R 匯出的修剪後政黨 DFM(23 × 5,474)。選目標政黨,JS 用 2 × 2 列聯表的 χ²(無連續性校正)計算每個特徵的 keyness;這個算法對 Conservative 與 Labour 都與 R textstat_keyness() 的輸出一致(下方自動比對)。
試試看:把「最小目標次數」調到 20,再看 Conservative 的前 15 名。
只出現在少數發言、參考組為 0 的字(例如 cyberstalking、icmp)會被濾掉一部分,留下比較「普遍」的差異。這是一種敏感度檢查(投影片 59 的 Full/trimmed vocabulary):如果結論只靠幾個罕見字,就不夠穩。注意:最小次數篩選是本教材加的探索選項,textstat_keyness() 本身沒有這個參數。
追蹤一個特徵的時間趨勢
hoc_dfm_year_conservative <- dfm(hoc_tokens_dfm)
hoc_dfm_year_conservative <- dfm_subset(
hoc_dfm_year_conservative,
party == "Conservative"
)
hoc_dfm_year_conservative <- dfm_group(
hoc_dfm_year_conservative,
groups = docvars(hoc_dfm_year_conservative, "year")
)
docvars(hoc_dfm_year_conservative, "economy") <- as.numeric(
hoc_dfm_year_conservative[, "economy"]
)
economy_by_year <- docvars(hoc_dfm_year_conservative)
ggplot(economy_by_year, aes(x = as.integer(year), y = economy)) +
geom_line() +
geom_point(size = 1) +
labs(
x = NULL,
y = "Frequency of 'economy'",
title = "Conservative mentions of economy in the teaching sample"
) +
theme_minimal()這是樣本中的原始次數。某一年的點比較高,可能只是那年抽到更多發言,不一定是更常用 economy;也不代表更關心或更支持。(Lab 說明)下面的互動讓你把原始次數換成「每千個 token」看看。
互動:特徵時間序列(原始次數 vs. 每千 token)
R 匯出了 Conservative 與 Labour 每年的 token 總數、發言數,以及 – 個特徵的逐年次數(DFM 用的 tokens,含合併後的搭配詞)。選「原始次數」時,Conservative 的 economy 應與上圖相同。
自我檢查
dim(hoc_dfm_party) 是 23 × 30640。23 是什麼?padding = TRUE?練習 1–11:先自己寫,再對答案
Lab 的 11 題練習重用前面的範例區塊。一次只改一個輸入,並說明輸出代表什麼。練習 5 接在 4 後面;10–11 接在 9 後面。(Lab 說明)
怎麼用這一章
- 每題有作答區(自動存在這台瀏覽器)。寫完按「複製成 R 註解」,可以直接貼進你的 .R 檔。
- 「看參考答案」展開的是
answers/Lab_Session_W2_Answers.R的程式碼與本機實際輸出(與老師 HTML 一致)。 - 老師的提醒:光是讓腳本跑完不算完成練習;要能解釋你的程式改變了什麼、怎麼影響證據。
11 題練習
str_detect()建立字元向量 speaker_names,內容是 hoc 前 20 位講者名字。用 str_detect() 找出哪些包含 Sir。
看參考答案(程式碼+本機輸出)
speaker_names <- hoc$speaker[1:20] speaker_names str_detect(speaker_names, "Sir") speaker_names[str_detect(speaker_names, "Sir")]
> speaker_names <- hoc$speaker[1:20] > speaker_names [1] "Mr. Johnstone" "Mr. Woodburn" "Mr. Eden" [4] "Vice-Admiral Taylor" "Sir M. Sueter" "Mr. Johnston" [7] "Sir J. Anderson" "Major Mills" "Mr. Viant" [10] "Earl Winterton" "Mr. Sorensen" "Sir J. Anderson" [13] "Mr. Kendall" "Sir M. Sueter" "The Prime Minister" [16] "Mr. McNeil" "Mr. H. Morrison" "Mr. Turton" [19] "Sir D. Somervell" "Mr. Loftus" > str_detect(speaker_names, "Sir") [1] FALSE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE FALSE FALSE TRUE [13] FALSE TRUE FALSE FALSE FALSE FALSE TRUE FALSE > speaker_names[str_detect(speaker_names, "Sir")] [1] "Sir M. Sueter" "Sir J. Anderson" "Sir J. Anderson" "Sir M. Sueter" [5] "Sir D. Somervell"
5 個符合(第 5、7、12、14、19 位);Sir J. Anderson 與 Sir M. Sueter 各出現兩次——同一人多次發言。
str_extract_all()用 str_extract_all() 從前 20 個 speech_url 抽出所有四位數年份。
看參考答案
speech_urls_20 <- hoc$speech_url[1:20]
str_extract_all(speech_urls_20, "\\b\\d{4}\\b")> speech_urls_20 <- hoc$speech_url[1:20]
> str_extract_all(speech_urls_20, "\\b\\d{4}\\b")
[[1]]
[1] "1945"
[[2]]
[1] "1945"
[[3]]
[1] "1945"
[[4]]
[1] "1945"
[[5]]
[1] "1945"
[[6]]
[1] "1945"
[[7]]
[1] "1945"
[[8]]
[1] "1945"
[[9]]
[1] "1945"
[[10]]
[1] "1945"
[[11]]
[1] "1945"
[[12]]
[1] "1945" "1914"
[[13]]
[1] "1945" "1945"
[[14]]
[1] "1945"
[[15]]
[1] "1945"
[[16]]
[1] "1945"
[[17]]
[1] "1945"
[[18]]
[1] "1945"
[[19]]
[1] "1945"
[[20]]
[1] "1945"加上 \\b 之後,網址錨點裡的 19450116 這類長數字不會被誤抓。但第 12 個網址多抓到 “1914”、第 13 個抓到兩個 “1945”——它們來自網址裡的議程標題:第 12 個是 …/1945/mar/06/war-gratuities-1914-18#…(議程 “WAR GRATUITIES, 1914–18”),第 13 個是 navy-estimates-1945-1,不是發言日期(本機 R 查證)。「四位數」不等於「年份」,要看上下文。
建立新變數 mentions_prime_minister,偵測發言文字中是否有 Prime Minister。有多少篇發言提到?
看參考答案
hoc <- hoc |>
mutate(
mentions_prime_minister = str_detect(
str_to_lower(text),
"\\bprime minister\\b"
)
)
sum(hoc$mentions_prime_minister)> hoc <- hoc |> + mutate( + mentions_prime_minister = str_detect( + str_to_lower(text), + "\\bprime minister\\b" + ) + ) > sum(hoc$mentions_prime_minister) [1] 279
279 篇(不分大小寫、字界)。注意這是「至少提到一次」的發言數,不是總次數。
corpus_subset()用 corpus_subset() 建一個 2016 年起的 Conservative 發言 corpus。有幾份文件?
看參考答案
conservative_since_2016 <- corpus_subset( hoc_corpus, party == "Conservative" & year >= 2016 ) ndoc(conservative_since_2016) summary(conservative_since_2016, n = 5)
> conservative_since_2016 <- corpus_subset(
+ hoc_corpus,
+ party == "Conservative" & year >= 2016
+ )
> ndoc(conservative_since_2016)
[1] 368
> summary(conservative_since_2016, n = 5)
corpus of 368 documents, showing 5 documents:
Text Types Tokens Sentences date
text4383 53 68 3 2016-01-11
text4384 95 143 7 2016-01-18
text4385 66 80 5 2016-01-18
text4387 81 133 8 2016-01-28
text4388 34 39 2 2016-01-28
agenda
Contraband: Entry into UK [Oral Answers to Questions > Home Department]
Soft Power [Oral Answers to Questions > Defence]
Nuclear Deterrent [Oral Answers to Questions > Defence]
Arms Sales to Saudi Arabia
NHS and Social Care Commission
speechnumber speaker party party.facts.id chair terms
43 James Brokenshire Conservative 1567 FALSE 64
75 Edward Leigh Conservative 1567 FALSE 129
100 Michael Fallon Conservative 1567 FALSE 73
266 Tobias Ellwood Conservative 1567 FALSE 116
410 Chris Davies Conservative 1567 FALSE 34
speech_url parliament iso3country party_raw year
<NA> UK-HouseOfCommons GBR Con 2016
<NA> UK-HouseOfCommons GBR Con 2016
<NA> UK-HouseOfCommons GBR Con 2016
<NA> UK-HouseOfCommons GBR Con 2016
<NA> UK-HouseOfCommons GBR Con 2016
agenda_clean
Contraband: Entry Into Uk
Soft Power
Nuclear Deterrent
Arms Sales To Saudi Arabia
Nhs And Social Care Commission368 份。
corpus_reshape()(接練習 4)把練習 4 的 corpus 改成句子單位。有幾份句子層級的文件?
看參考答案
conservative_sentences <- corpus_reshape( conservative_since_2016, to = "sentences" ) ndoc(conservative_sentences) as.character(conservative_sentences)[1:5]
> conservative_sentences <- corpus_reshape( + conservative_since_2016, + to = "sentences" + ) > ndoc(conservative_sentences) [1] 2995 > as.character(conservative_sentences)[1:5] text4383.1 "We are taking this forward at a European level." text4383.2 "My right hon." text4383.3 "Friend the Home Secretary is in discussions with other European leaders on how best we can co-ordinate with and lobby Governments beyond Europe as well, to share the focus that we as a Government have on confronting the smuggling of weapons and ensuring that this issue is dealt with even more firmly." text4384.1 "Will the Minister make a comment about increasing our security in the Baltic region in relation to soft power?" text4384.2 "In the context of soft power, may I apologise on behalf of my right hon."
368 篇 → 2,995 個句子,平均每篇約 8 句。
切字並保留 Prime Minister、European Union、House of Commons 三個多字詞,再用 kwic() 檢查 Prime_Minister。
看參考答案
hoc_tokens_exercise <- tokens(
hoc_corpus,
remove_punct = TRUE,
remove_symbols = TRUE,
remove_numbers = FALSE
)
hoc_tokens_exercise <- tokens_compound(
hoc_tokens_exercise,
pattern = phrase(c(
"Prime Minister",
"European Union",
"House of Commons"
))
)
kwic(
hoc_tokens_exercise,
pattern = phrase("Prime_Minister"),
window = 8
) |>
head(10)> hoc_tokens_exercise <- tokens(
+ hoc_corpus,
+ remove_punct = TRUE,
+ remove_symbols = TRUE,
+ remove_numbers = FALSE
+ )
> hoc_tokens_exercise <- tokens_compound(
+ hoc_tokens_exercise,
+ pattern = phrase(c(
+ "Prime Minister",
+ "European Union",
+ "House of Commons"
+ ))
+ )
> kwic(
+ hoc_tokens_exercise,
+ pattern = phrase("Prime_Minister"),
+ window = 8
+ ) |>
+ head(10)
Keyword-in-context with 10 matches.
[text16, 30] to say that he could answer for the |
[text43, 239] very strong and public support from the then |
[text52, 41] appropriateness In fact my right hon Friend the |
[text52, 49] Prime_Minister has lately been in touch with the |
[text156, 363] a letter from my right hon Friend the |
[text278, 7] At least he can consult the |
[text280, 16] for the words that have fallen from the |
[text424, 3] asked the |
[text544, 3] asked the |
[text544, 27] of the United States of America and the |
Prime_Minister | but I can say that when the Home
Prime_Minister | and the Government of this country When the
Prime_Minister | has lately been in touch with the Prime_Minister
Prime_Minister | of Canada on this and other matters
Prime_Minister | that this matter is being considered at the
Prime_Minister | over this matter and see whether it cannot
Prime_Minister | of Northern Ireland and from his Minister of
Prime_Minister | if the speech of the Secretary of State
Prime_Minister | whether in view of his welcome restoration to
Prime_Minister | of France to resume the arrangements for the 很多是 “asked the Prime_Minister” 或 “my right hon Friend the Prime_Minister”——提到首相常常只是議會的提問格式,不是在「談」首相。
agenda 與 agenda_clean 各數出最常見的 10 個值。清理後改變了什麼?
看參考答案
hoc |> count(agenda, sort = TRUE) |> head(10) hoc |> count(agenda_clean, sort = TRUE) |> head(10) # Cleaning collapses capitalization differences such as "BUSINESS OF THE HOUSE", # "Business of the House", and "Business Of The House" into one label. It also # collapses agenda labels beginning with "Engagements" into a common # "Engagements" category.
> hoc |>
+ count(agenda, sort = TRUE) |>
+ head(10)
agenda
1 <NA>
2 BUSINESS OF THE HOUSE
3 Business of the House
4 Business Of The House
5 Topical Questions
6 Engagements [Oral Answers to Questions > Prime Minister]
7 Engagements
8 Engagements [Oral Answers To Questions > Prime Minister > Prime Minister]
9 Finance Bill
10 European Council
n
1 206
2 56
3 54
4 34
5 24
6 23
7 18
8 18
9 12
10 9
> hoc |>
+ count(agenda_clean, sort = TRUE) |>
+ head(10)
agenda_clean n
1 <NA> 206
2 Business of the House 151
3 Engagements 81
4 Topical Questions 69
5 Finance Bill 18
6 Points of Order 15
7 European Economic Community 14
8 Debate On The Address 12
9 Budget Resolutions And Economic Situation 11
10 Northern Ireland 11
> # Cleaning collapses capitalization differences such as "BUSINESS OF THE HOUSE",
> # "Business of the House", and "Business Of The House" into one label. It also
> # collapses agenda labels beginning with "Engagements" into a common
> # "Engagements" category.清理把 “BUSINESS OF THE HOUSE”(56)、“Business of the House”(54)、“Business Of The House”(34)等合成一個標籤(151),也把 Engagements 開頭的變體合成 81 筆。NA 206 筆不變。
在 hoc_tokens_dfm 中顯示最強的三特徵搭配詞(依 lambda 排序)。有些特徵已經是合併過的字,所以不一定是三個原始字。
看參考答案
textstat_collocations( hoc_tokens_dfm, size = 3, min_count = 5 ) |> arrange(desc(lambda)) |> head(20)
> textstat_collocations(
+ hoc_tokens_dfm,
+ size = 3,
+ min_count = 5
+ ) |>
+ arrange(desc(lambda)) |>
+ head(20)
collocation count count_nested length lambda z
34 transport general workers 7 0 3 8.119809 3.275857
22 european economic community 9 0 3 8.026347 3.671224
51 state commonwealth relations 5 0 3 7.126365 2.861315
3 state home department 28 0 3 7.099060 5.618443
35 lords said amendment 5 0 3 6.967612 3.249923
39 national farmers union 11 0 3 6.925794 3.171465
45 general workers union 6 0 3 6.641970 3.021601
42 department work pensions 7 0 3 6.549383 3.148884
46 general needs housing 6 0 3 6.343273 3.007404
12 private members time 8 0 3 6.288444 3.986629
44 national coal board 14 0 3 6.277167 3.039486
43 greater london council 12 0 3 6.241621 3.057219
81 lord chief justice 9 0 3 6.119386 2.472207
82 environment food rural 13 0 3 6.042873 2.446875
65 town country planning 5 0 3 5.879678 2.664581
52 home department whether 6 0 3 5.865489 2.861206
30 bill now read 6 0 3 5.864393 3.445057
55 asked president board 29 0 3 5.768125 2.852030
9 minister pensions national 10 0 3 5.610909 4.647448
38 hold government account 5 0 3 5.527632 3.193026transport general workers、european economic community、state home department……注意「state home department」很可能是 “Secretary of State for the Home Department” 刪掉停用字後的殘留:到了練習 8,hoc_tokens_dfm 已經在 compound_collocations_for_dfm 那一步用 tokens_remove(hoc_tokens_dfm, "") 移除了 padding,所以原本隔著 for、the 的字變成相鄰——正是投影片 32 警告的情況(本教材的解讀,非講義內容)。
從 hoc_tokens_dfm 建 DFM 並依 party 分組,命名為 hoc_dfm_exercise。有幾份文件、幾個特徵?
看參考答案
hoc_dfm_exercise <- dfm(hoc_tokens_dfm) hoc_dfm_exercise <- dfm_group( hoc_dfm_exercise, groups = docvars(hoc_dfm_exercise, "party") ) dim(hoc_dfm_exercise) topfeatures(hoc_dfm_exercise, 20)
> hoc_dfm_exercise <- dfm(hoc_tokens_dfm)
> hoc_dfm_exercise <- dfm_group(
+ hoc_dfm_exercise,
+ groups = docvars(hoc_dfm_exercise, "party")
+ )
> dim(hoc_dfm_exercise)
[1] 23 30640
> topfeatures(hoc_dfm_exercise, 20)
hon government right member can people one
6569 3213 2780 2428 2423 2296 2288
friend minister house made many members time
2279 2049 2000 1600 1537 1515 1503
bill said gentleman may make secretary
1484 1484 1372 1351 1343 1340 23 × 30,640,與 Lab 範例的 hoc_dfm_party 相同。
修剪 hoc_dfm_exercise,只保留至少出現 20 次的特徵。看看新的維度。
看參考答案
hoc_dfm_exercise_trimmed <- dfm_trim( hoc_dfm_exercise, min_termfreq = 20 ) dim(hoc_dfm_exercise) dim(hoc_dfm_exercise_trimmed)
> hoc_dfm_exercise_trimmed <- dfm_trim( + hoc_dfm_exercise, + min_termfreq = 20 + ) > dim(hoc_dfm_exercise) [1] 23 30640 > dim(hoc_dfm_exercise_trimmed) [1] 23 3424
30,640 → 3,424。第 11 章的修剪互動可以拖到 20 驗證。
用 textstat_keyness() 顯示 Labour 相對於其他所有政黨最有區辨力的特徵。
看參考答案
labour_keyness <- textstat_keyness( hoc_dfm_exercise_trimmed, target = docnames(hoc_dfm_exercise_trimmed) == "Labour" ) head(labour_keyness, 10) textplot_keyness(labour_keyness, n = 10)
> labour_keyness <- textstat_keyness(
+ hoc_dfm_exercise_trimmed,
+ target = docnames(hoc_dfm_exercise_trimmed) == "Labour"
+ )
> head(labour_keyness, 10)
feature chi2 p n_target n_reference
1 waste 73.18169 0.000000e+00 124 38
2 advertising 51.95577 5.676570e-13 64 12
3 giro 44.03569 3.224421e-11 36 1
4 tory 43.68173 3.863621e-11 73 22
5 glc 42.34350 7.657031e-11 37 2
6 child 34.35619 4.589373e-09 165 106
7 conservative 34.18764 5.004582e-09 203 142
8 lottery 33.09979 8.754839e-09 32 3
9 nuclear 32.45001 1.222982e-08 120 68
10 illegitimate 29.64764 5.181577e-08 25 1
> textplot_keyness(labour_keyness, n = 10)textplot_keyness(labour_keyness, n = 10)(本機 R 產生)。waste、advertising、giro、tory、glc……tory 與 conservative 出現在 Labour 的 keyness 前面,一個可能的解讀是 Labour 議員常在辯論中點名對手(本教材解讀,要用 KWIC 確認)——keyness 抓到的可能是「誰在說誰」,不是政策立場。這份用的是門檻 20 的 DFM,和 Conservative 範例(門檻 10)不同,比較兩者時要注意。
答案摘要表(本機輸出)
| 練習 | 關鍵數字 |
|---|---|
| 1 | 前 20 位講者中 5 個含 Sir |
| 3 | 279 篇提到 prime minister |
| 4/5 | 2016 起 Conservative:368 篇 → 2,995 句 |
| 7 | Business of the House:清理前分散成 56/54/34…,清理後 151 |
| 9/10 | 23 × 30,640 → 23 × 3,424(min_termfreq = 20) |
| 11 | Labour 前三:waste(χ² 73.18)、advertising(51.96)、giro(44.04) |
自我檢查
"\\b\\d{4}\\b" 抓年份,第 12 個網址抓到 “1945” 和 “1914”。正確的解讀是?文獻導讀與課堂討論
課程 repo 的 W2/papers/ 有兩篇全文:Welbers, Van Atteveldt & Benoit (2017) 與 Benoit et al. (2018)。導讀卡只根據這兩份 PDF,頁碼是期刊頁碼。其他投影片提到的研究,本教材沒有全文,只轉述投影片。
Welbers, K., Van Atteveldt, W., & Benoit, K. (2017). Text Analysis in R. Communication Methods and Measures 11(4): 245–265.
來源:課程 repo W2/papers/Welbers2017.pdf(Taylor & Francis 版,22 頁 PDF;頁碼為期刊頁碼)。doi:10.1080/19312458.2017.1387238。
Benoit, K., Watanabe, K., Wang, H., Nulty, P., Obeng, A., Müller, S., & Matsuo, A. (2018). quanteda: An R package for the quantitative analysis of textual data. Journal of Open Source Software 3(30): 774.
textmodel_* 實作 Wordscores、Wordfish、class affinity scaling、對應分析、Naive Bayes、LSA;文字統計包含頻率、keyness、詞彙多樣性、可讀性、相似度與距離(p. 2)。corpus()、tokens()、dfm() 建立物件;corpus_*()、tokens_*()、dfm_*() 回傳修改後的物件)、易用、效能、透明與可重現、與 stm、text2vec、spacyr 等套件相容(p. 3)。tokens_compound、dfm_group、dfm_trim、textstat_keyness、textplot_keyness。看到前綴就知道輸入與輸出是什麼物件。來源:課程 repo W2/papers/Benoit2018.pdf(JOSS,4 頁,CC BY 4.0)。doi:10.21105/joss.00774。
投影片提到、但本教材沒有全文的研究
下列研究的 PDF 不在課程 repo 裡,本教材沒有讀到全文,只轉述投影片 54–58、63 的內容(見第 09 章表格)。需要細讀的讀者,可透過台大圖書館或學校 VPN 取得全文:
- Roberts et al. (2014) STM;Eshima et al. (2024) keyATM。
- Slapin & Proksch (2008) Wordfish;Lowe (2008)、Laver et al. (2003) Wordscores。
- Blumenau (2021);Bestvater & Monroe (2023)。
- Grimmer, Roberts & Stewart (2022) Text as Data 第 4 章(書籍)。
- Schoonvelde (2026) Essex Summer School 投影片(投影片 64 稱為「主要講課來源」,38 頁)。
課堂討論
從前面介紹的應用論文挑一篇,先看它的研究問題與一張主要圖表:
- 研究問題是什麼?什麼算一份文件?
- 刪字、文件聚合或加權,可能怎麼影響這個量測?
- 除了「前處理成功」之外,什麼證據支持作者的詮釋?
候選:主題模型 Roberts et al. (2014)、Eshima et al. (2024);文本縮放 Slapin & Proksch (2008)、Laver et al. (2003);TF-IDF 應用 Blumenau (2021)、Bestvater & Monroe (2023)。
互動:主張判斷——這個說法站得住嗎?
每一句是一個可能出現在報告裡的主張(本教材自擬)。判斷「站得住」「需要更多證據」或「錯誤」,再看說明。
互動:討論準備卡
自我檢查
常見陷阱、詞彙表、總複習與參考文獻
把本週的選擇寫成一份「前處理決策紀錄」,以後做專題時直接沿用。
十個常見陷阱
| 陷阱 | 為什麼是問題 | 本週的證據 |
|---|---|---|
| 把可取得的文本當成母體 | 資源、誘因、媒介、檢索都會造成偏誤 | 投影片 4–5 |
| 覆蓋原始文字 | 無法檢查清理改了什麼 | Lab 另存 agenda_clean |
| 貪婪的 regex | \[.*\] 一路刪到最後一個 ] | “Trade ” |
| 沒加字界 | war 比到 warfare、towards | Lab word_boundary_examples |
| 標準停用字表刪掉否定 | d3 的句意反轉 | workers support policy |
| 先刪字再做 bigram | 造出不存在的配對 | workers_support |
| 只留 NOUN/VERB | 否定詞「不」(ADV)消失 | 投影片 42 |
| 修剪掉罕見但關鍵的字 | min_docfreq = 2 刪掉 not | 投影片 47 |
| 把原始次數當成關注程度 | 分母(發言數、token 數)每年不同 | economy 逐年圖(第 11 章) |
| 把 keyness 當成立場或情緒 | 它只是用字比較,常被議會用語與少數長發言主導 | hon、friend、cyberstalking(第 11 章) |
詞彙表(可搜尋)
總複習
前處理決策紀錄(為你的專題)
投影片 2 的目標 3 要你檢查專題資料的可行性(coverage、metadata、access);投影片 59 要你對選定的規則做敏感度比較。把答案寫下來,之後可以直接放進專題的資料與方法段落。
我的進度
只會清除這份 W2 教材的紀錄。
參考文獻與軟體
投影片 64 列出的
- Schoonvelde, M. (2026). Quantitative text analysis – Essex Summer School: Principles of QTA, cleaning text, and preprocessing text. Supplied slides, 38 pages.(主要講課來源)
- Welbers, K., Van Atteveldt, W., & Benoit, K. (2017). Text Analysis in R. Communication Methods and Measures, 11(4), 245–265. doi:10.1080/19312458.2017.1387238.(閱讀與重製的圖表)
- Grimmer, J., Roberts, M. E., & Stewart, B. M. (2022). Text as Data: A New Framework for Machine Learning and the Social Sciences. Princeton University Press. Chapter 4: “Selecting Documents.”
- 軟體文件:quanteda(tokens、TF-IDF、KWIC)、stringr(pattern removal);UDPipe guide、Japanese GSD、Chinese GSD。
- 投影片中的英文、泰文、日文與中文例句是合成的教學例子。
投影片其他頁引用的
- Benoit, K., et al. (2018). quanteda: An R package for the quantitative analysis of textual data. JOSS 3(30): 774. doi:10.21105/joss.00774.
- Straka, M., & Straková, J. (2017);Straka, M. (2018)(UDPipe);Wijffels, J., & Straka, M. (2026)(R udpipe);Universal Dependencies contributors (n.d.)。
- Akbik, A., et al. (2018, 2019)(Flair);Liao, Y.-C., et al. (2023)(flaiR);Wolf, T., et al. (2020)(Transformers);Sentence Transformers contributors (n.d.);Explosion (n.d.)(spaCy)。
- Ushey, K., et al. (2026)(reticulate);Posit (2022, n.d.);Altman (2025);R Core Team (n.d.);Python Software Foundation (n.d.);Wickham, H. (2025)(stringr)。
- Roberts, M. E., et al. (2014);Eshima, S., et al. (2024);Slapin, J. B., & Proksch, S.-O. (2008);Laver, M., Benoit, K., & Garry, J. (2003);Lowe, W. (2008);Lowe & Benoit (2013);Blei, Ng & Jordan (2003);Roberts et al. (2019);Blumenau, J. (2021);Bestvater, S., & Monroe, B. (2023)。
Lab 來源
- 改編自 Martijn Schoonvelde (2026), QTA Lab 02: String Operations and Inspecting the House of Commons Corpus,並致謝 Stefan Müller 的早期材料;保留原始分析範例與 11 題練習。