如何在Shiny中循环搜索关键字搜索中所有可能的句子?

问题描述

我创建了一个文本搜索,其中搜索一个单词,显示其中包含该单词的所有句子。但是,当我需要显示上载文本中基于该单词的所有句子时,我只会在Shiny中得到输出的第一句话。

library(quanteda)
library(shiny)
library(tidyverse)
library(htmltools)
library(shinythemes)


war <- readLines("war.txt")


war_corpus <- corpus(war)


sentences <- tokens(war_corpus,what="sentence")


make_sentences <- function(word) {
  grep(word,sentences,value= TRUE)}


sentence_line <- function(word) {
  grep(word,value= FALSE)}



ui<- shinyUI(fluidPage(
  
  
  # Application title
  mainPanel(
    img(src='image.jpg',align = "right"),br(),fluidRow(
      column(2,h5(HTML("<strong>Enter a word.Click \"SEARCH\" </strong>")),wellPanel(
               textInput("inputString","Enter a word here",value=" "),submitButton("Search"),)),column(5,h4("Search Results"),wellPanel(                       
               tags$style("#mytext { white-space: pre-line; }"),htmlOutput("mytext")
             )),offset = 1.5,h6("Uploaded File"),wellPanel(
               htmlOutput("showfile"))
      )
    )
    
  ),#Mainpanel
  
)#fluidpage
)#shinyUi



server <- function(input,output,session) {
  output$mytext <- renderUI({
    
    res <- make_sentences(input$inputString)[1]
    res1<- sentence_line(input$inputString)[1]
    tagList(
      tags$a(href=paste('#',res1,sep=""),res1),tags$div(res)
    )
    
  })
  output$showfile <- renderText({
    includeHTML("www/final_tokens.html")
  })
}
shinyApp(ui,server)

正如您在屏幕快照中看到的那样,对于单词'good'我得到的是第一句话,而实际上我应该从txt文件获取所有单词'good'的句子(例如单词'good'中的27个句子) )

enter image description here

解决方法

那是因为[1]。在renderUI中,输入:

res <- make_sentences(input$inputString)
res1 <- sentence_line(input$inputString)
divs <- mapply(
  function(line,sentence){
    tags$div(tags$a(href = paste0("#",line),tags$p(sentence))
  },res1,res,SIMPLIFY = FALSE)
do.call(tagList,divs)