[英]Quanteda dfm_lookup using dictionaries with multi-word patterns/expressions
[英]Construct a character vector of multi-word phrases using regex for building dfm using quanteda in R
我曾經非常滿意Quanteda的textstat_collocation()來提取MWE。 現在,我嘗試提取與特定模式匹配的所有匹配項,而不考慮它們的出現頻率。
我的目標是通過從使用正則表達式模式構建的dfm()中提取功能名稱來創建字符向量。 然后,我將在“選擇”參數中使用此字符向量來構建dfm。 我可能還想使用此字符向量將其添加到字典中,該字典將用作在管道后期構建dfms的本體。
模式是:“ xx-xx歲”,其中x是數字。
我在這里使用了正則表達式模式“ aged \\ s([0-9] {2}-[0-9] {2})” ,並獲得了所需的匹配項。 但是,當我在R中嘗試(在“ \\ s”之前添加一個附加的“ \\”)時,沒有任何匹配。
當我做:
txt <- c("In India, male smokers aged 20-45 perceive brandX positively.",
"In Spain, female buyers aged 30-39 don't purchase brandY.")
ageGroups <- dfm(txt, select = "aged\\s([0-9]{2}-[0-9]{2})", valuetype = "regex")
featnames(ageGroups)
我得到:
character(0)
但是,當我嘗試:
ageGroups <- dfm(txt, select = "([0-9]{2}-[0-9]{2})", valuetype = "regex")
featnames(ageGroups)
我得到:
[1] "20-45" "30-39"
看來我無法捕獲正則表達式中的空白。 我在SO中經歷了許多類似的問題,也許這是最相關的,但仍然無法使我的特定目標發揮作用。
我也嘗試過:
tokens <- tokens(txt, remove_punct = FALSE, remove_numbers = FALSE, remove_symbols = FALSE)
tokensCompunded <- tokens_compound(tokens, pattern = "aged\\s([0-9]{2}-[0-9]{2})", valuetype = "regex")
attr(tokensCompunded, "types")
但是我得到了所有令牌:
[1] "In" " " "India" "," "male" "smokers" "aged" "20-45" "perceive"
[10] "brandX" "positively" "." "Spain" "female" "buyers" "30-39" "don't" "purchase"
[19] "brandY"
我認為可能還有其他一些更有效的方法使用帶有ededa的正則表達式(或glob)來提取字符向量,我很高興學習如何使用此驚人R包的新方法。
謝謝你的幫助!
編輯原始問題:
這在其他SO問題也有類似的要求,即,使用對象KWIC檢測多字短語,並且可以進一步擴展以實現與下面的加成上述的目標:
kwicObject <- kwic(corpus, pattern = phrase("aged ([0-9]{2}-[0-9]{2})"), valuetype = "regex")
unique(kwicObject$keyword)
您可以更改正則表達式模式:
select = "aged.*([0-9]{2}-[0-9]{2})"
這里的問題是目標文本和多字pattern
(包含空格)沒有以相同的方式標記。 在您的示例中,您為多個標記(包括空格分隔符)應用了一個正則表達式,但是搜索目標已被拆分為單個標記。
我們為此設計了一個解決方案,即一個稱為phrase()
的函數。 來自?pattern
:
空格沒有特權,因此在字符向量中,空格按字面意義進行解釋。 如果您希望將以空格分隔的元素視為標記序列,請將參數包裝在
phrase()
。
因此,在這種情況下:
pat <- "aged [0-9]{2}-[0-9]{2}"
toks2 <- tokens_select(toks, pattern = phrase(pat), valuetype = "regex")
toks2
# tokens from 2 documents.
# text1 :
# [1] "aged" "20-45"
#
# text2 :
# [1] "aged" "30-39"
在這里,我們看到選擇是有效的,因為phrase()
包裝器將模式轉換為匹配序列。
如果要將這些作為單個令牌,則可以將相同的pattern
參數發送給tokens_compound()
:
toks3 <- tokens_compound(toks2, pattern = phrase(pat),
valuetype = "regex", concatenator = " ")
toks3
# tokens from 2 documents.
# text1 :
# [1] "aged 20-45"
#
# text2 :
# [1] "aged 30-39"
最后,您可以使用它來構建dfm,其中每個多字匹配都是一個功能。 除非您首先在令牌階段執行串聯,否則這將無法工作,因為根據定義,dfm的功能沒有順序。
dfm(toks3)
# Document-feature matrix of: 2 documents, 2 features (50% sparse).
# 2 x 2 sparse Matrix of class "dfm"
# features
# docs aged 20-45 aged 30-39
# text1 1 0
# text2 0 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.