開始使用免費開始

擷取姓名與其前後文

讓我們再回到瑞士政治人物的資料集。它包含兩個變數:articles 是一組與瑞士政治相關的新聞文章,politicians 則是數個瑞士政治人物姓名所組成的向量。

你已經計算過每個姓名出現的次數。不過,若不只計數,還能看到這些姓名出現時的前後脈絡,不是更有意思嗎?例如,你可以比較女性與男性政治人物在脈絡上是否有所不同。為了做到這點,你需要擷取政治人物姓名周圍的文字。

由於本文同時包含單字字元 \\w 與像句點 .、逗號 , 之類的標點 [:punct:],你需要建立一個同時能比對這兩種字元的樣式。

本練習屬於課程

R 中級 Regular Expressions

檢視課程

練習說明

  • 使用向量 politicians,將其串接成一個「or 樣式」,就像你在第 2 章所做的那樣。
  • 在方括號 [] 中建立一個自訂樣式,能同時比對單字字元與標點符號。
  • 使用 glue,將新建立的 context 同時加在 polit_pattern 的前後。\\s? 表示在政治人物姓名之後可以有空白或沒有空白。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Create our polit_pattern again by collapsing "politicians"
polit_pattern <- glue_collapse(___, sep = "|")

# Match one or more word characters or punctuations
context <- "([___[___]]+\\s){0,10}"

# Add this pattern in front and after the polit_pattern
polit_pattern_with_context <- glue(
  "{___}({polit_pattern})\\s?{___}"
)

str_extract_all(
  articles$text,
  pattern = polit_pattern_with_context
)
編輯並執行程式碼