[英]Find all possible phrase matches between string and lookup table
我有一個帶有一堆文本字符串的數據框。 在第二個數據框中,我有一個短語列表,用作查找表。 我想在查找表中搜索所有可能的短語匹配的文本字符串。
我的問題是某些短語有重疊的單詞。 例如:“雞蛋”和“綠色雞蛋”。
library(udpipe)
library(dplyr)
# Download english dictionary
ud_model <- udpipe_download_model(language = "english")
ud_model <- udpipe_load_model(ud_model$file_model)
# Create example data
sample <- data.frame(doc_id = 1, text = "the cat in the hat ate green eggs and ham")
phrases <- data.frame(phrase = c("cat", "hat", "eggs", "green eggs", "ham", "the cat"))
# Tokenize text
x <- udpipe_annotate(ud_model, x = sample$text, doc_id = sample$doc_id)
x <- as.data.frame(x)
x$token <- tolower(x$token)
test_results <- x %>% select(doc_id, token)
test_results$term <- txt_recode_ngram(test_results$token,
compound = phrases$phrase,
ngram = str_count(phrases$phrase, '\\w+'),
sep = " ")
# Remove any tokens that don't match a phrase in the lookup table
test_results <- filter(test_results, term %in% phrases$phrase)
在結果中,您可以看到返回的是“the cat”而不是“cat”,返回的是“green eggs”而不是“eggs”。
> test_results$term
[1] "the cat" "hat" "green eggs" "ham"
如何在文本字符串和查找表之間找到所有可能的短語匹配?
我應該補充一點,我不喜歡任何特定的 package。 我只是在這里使用 udpipe,因為我最熟悉它。
我認為如果一個字符串在另一個字符串中,您可以簡單地使用grepl
來匹配。 從那里您apply
grepl
應用於所有其他匹配模式
# Create example data
sample <- data.frame(doc_id = 1, text = "the cat in the hat ate green eggs and ham")
phrases <- data.frame(phrase = c("cat", "hat", "eggs", "green eggs", "ham", "the cat"))
apply(phrases, 1, grepl,sample$text)
如果你想要你的比賽,你可以:
phrases[apply(phrases, 1, grepl,sample$text),]
但也許dataframe
類型與短語不是最相關的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.