我工作(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