我工作(R與openNLP)從提供的語句中提取數字數據。從R語句中提取數值數據?
的語句是"The room temperature is 37 to 39 C. The Air flow is near 80 cfm".
這裏的預期輸出"Temperature > 37 - 39c",
"Air flow -> 80cfm"
。
你可以建議POS標籤上的任何正則表達式模式來獲得名詞(NN)和下一個可用的數字數據(CD)嗎?
是否有任何替代方法來提取類似的數據?
我工作(R與openNLP)從提供的語句中提取數字數據。從R語句中提取數值數據?
的語句是"The room temperature is 37 to 39 C. The Air flow is near 80 cfm".
這裏的預期輸出"Temperature > 37 - 39c",
"Air flow -> 80cfm"
。
你可以建議POS標籤上的任何正則表達式模式來獲得名詞(NN)和下一個可用的數字數據(CD)嗎?
是否有任何替代方法來提取類似的數據?
從自然文本中提取數據很難!我預計這個解決方案會很快破解。但是,這是一種讓你開始的方法。你沒有提供整個標記的句子,所以我插入了我自己的標籤。您可能需要更改此標籤。此外,此代碼既不高效也不是矢量化的,只能用於單個字符串。
library(stringr)
text <- "The_DT room_NN temperature_NN is_VBZ 37_CD to_PRP 39_CD C_NNU. The_DT Air_NN flow_NN is_VBZ near_ADV 80_CD cfm_NNU"
# find the positions where a Number appears; it may be followed by prepositions, units and other numbers
matches <- gregexpr("(\\w+_CD)+(\\s+\\w+_(NNU|PRP|CD))*", text, perl=TRUE)
mapply(function(position, length) {
# extract all NN sequences
nouns <- text %>% str_sub(start = 1, end = position) %>%
str_extract_all("\\w+_NN(\\s+\\w+_NN)*")
# get Numbers
nums <- text %>% str_sub(start=position, end = position + length)
# format output string
result <- paste(tail(nouns[[1]], n=1), nums, sep = " > ")
# clean tags
gsub("_\\w+", "", result)
}, matches[[1]], attr(matches[[1]], "match.length"))
# output: [1] "room temperature > 37 to 39 C." "Air flow > 80 cfm"
也許你可以從下面的方法開始。希望這可以幫助!
library(NLP)
library(openNLP)
library(dplyr)
s <- "The room temperature is 37 to 39 C. The Air flow is near 80 cfm"
sent_token_annotator <- Maxent_Sent_Token_Annotator()
word_token_annotator <- Maxent_Word_Token_Annotator()
a2 <- annotate(s, list(sent_token_annotator, word_token_annotator))
pos_tag_annotator <- Maxent_POS_Tag_Annotator()
a3 <- annotate(s, pos_tag_annotator, a2)
#distribution of POS tags for word tokens
a3w <- subset(a3, type == "word")
#select consecutive NN & CD POS
a3w_temp <- a3w[sapply(a3w$features, function(x) x$POS == "NN" | x$POS == "CD")]
a3w_temp_df <- as.data.frame(a3w_temp)
#add lead 'features' to dataframe and select rows having (NN, CD) or (NN, CD, CD) sequence
a3w_temp_df$ahead_features = lead(a3w_temp_df$features,1)
a3w_temp_df$features_comb <- paste(a3w_temp_df$features,a3w_temp_df$ahead_features)
l <- row.names(subset(a3w_temp_df, features_comb == "list(POS = \"NN\") list(POS = \"CD\")" |
features_comb == "list(POS = \"CD\") list(POS = \"CD\")"))
l_final <- sort(unique(c(as.numeric(l), as.numeric(l) +1)))
a3w_df <- a3w_temp_df[l_final,]
#also include POS which is immediately after CD
idx <- a3w_df[a3w_df$features=="list(POS = \"CD\")","id"]+1
idx <- sort(c(idx,a3w_df$id))
op = paste(strsplit(s, split = " ")[[1]][idx -1], collapse = " ")
op
輸出是:
[1] "temperature 37 to 39 C. flow 80 cfm"
@Dhana你應該把它標記爲正確的答案,如果它回答了你的查詢作爲它會幫助其他人的情況下,他們面臨着類似的問題在未來。謝謝! – Prem