2016-12-12 9 views
6

mam dokumentów, takich jak:Podział głośników i dialog w RStudio

prezydenta dr Norbert Lammert: Oświadczam sesja otwarta.

Teraz oddam głos Bundesministerowi Alexandrowi Dobrindtowi.

(Oklaski z CDU/CSU i SPD delegaci)

Alexander Dobrindt, minister transportu i infrastruktury cyfrowej:

Panie i Panowie. Dziś rozpoczniemy największą inwestycję w infrastrukturę, która kiedykolwiek istniała, z ponad 270 miliardami euro, ponad 1 000 projektów i przejrzystą perspektywą finansowania.

(Volker Kauder [CDU/CSU]: Genau)

(Oklaski z CDU/CSU i SPD)

I kiedy czytam te dokumenty .txt Chciałbym utworzyć druga kolumna wskazująca nazwę głośnika.

Więc co starałem się najpierw utworzyć listę wszystkich możliwych nazw i zastąpić je ..

library(qdap) 

members <- c("Alexander Dobrindt, Minister for Transport and Digital Infrastructure:","President Dr. Norbert Lammert:") 
members_r <- c("@Alexander Dobrindt, Minister for Transport and Digital Infrastructure:","@President Dr. Norbert Lammert:") 

prok <- scan(".txt", what = "character", sep = "\n") 
prok <- mgsub(members,members_r,prok) 

prok <- as.data.frame(prok) 
prok$speaker <- grepl("@[^\\@:]*:",prok$prok, ignore.case = T) 

Mój plan był następnie uzyskać nazwę między @ a: poprzez regex jeśli głośnik == true i używaj go w dół, dopóki nie pojawi się inna nazwa (i oczywiście usuń wszystkie oklaski/okrzyki), ale to także nie wiem, w jaki sposób mogę to zrobić.

+0

Powodem, dla którego nie zwróciłeś uwagi na to pytanie jest pomylenie, Dlaczego oznaczasz to wi th RStudio (który jest całkowicie nieistotnym znacznikiem bez prawie żadnych obserwatorów), a nie z tagiem R (który jest odpowiednim znacznikiem i ma prawie 50 000 obserwujących)? –

+0

Dziękuję za wskazanie tego! Nie wiedziałem, na pewno zwrócę na to uwagę w przyszłości :) – erocoar

Odpowiedz

1

Tutaj jest podejście opierając się ciężko na dplyr.

Najpierw dodałem zdanie do przykładowego tekstu, aby zilustrować, dlaczego nie możemy po prostu użyć dwukropka do identyfikacji nazwisk głośników.

sampleText <- 
"President Dr. Norbert Lammert: I declare the session open. 

I will now give the floor to Bundesminister Alexander Dobrindt. 

(Applause of CDU/CSU and delegates of the SPD) 

Alexander Dobrindt, Minister for Transport and Digital Infrastructure: 

Ladies and Gentleman. We will today start the biggest investment in infrastructure that ever existed, with over 270 billion Euro, over 1 000 projects and a clear financing perspective. 

(Volker Kauder [CDU/CSU]: Genau!) 

(Applause of the CDU/CSU and the SPD) 

This sentence right here: it is an example of a problem" 

Następnie podzielić tekst do symulacji format że wydaje czytasz w (co stawia także każde przemówienie w ramach listy).

splitText <- strsplit(sampleText, "\n") 

Potem ja wyciągnięciu wszystkich potencjalnych głośników (coś, co poprzedza dwukropek) do

allSpeakers <- lapply(splitText, function(thisText){ 
    grep(":", thisText, value = TRUE) %>% 
    gsub(":.*", "", .) %>% 
    gsub("\\(", "", .) 
}) %>% 
    unlist() %>% 
    unique() 

co daje nam:

[1] "President Dr. Norbert Lammert"           
[2] "Alexander Dobrindt, Minister for Transport and Digital Infrastructure" 
[3] "Volker Kauder [CDU/CSU]"            
[4] "This sentence right here" 

Oczywiście, ten ostatni jest nie jest to uzasadniona nazwa, dlatego powinno być wykluczone z naszej listy głośników:

legitSpeakers <- 
    allSpeakers[-4] 

Teraz jesteśmy gotowi do pracy poprzez przemówienie. Mam włączone poniżej stopniowych komentarzy, zamiast opisywać w tekście tutaj

speechText <- lapply(splitText, function(thisText){ 

    # Remove applause and interjections (things in parentheses) 
    # along with any blank lines; though you could leave blanks if you want 
    cleanText <- 
    grep("(^\\(.*\\)$)|(^$)", thisText 
     , value = TRUE, invert = TRUE) 

    # Split each line by a semicolor 
    strsplit(cleanText, ":") %>% 
    lapply(function(x){ 
     # Check if the first element is a legit speaker 
     if(x[1] %in% legitSpeakers){ 
     # If so, set the speaker, and put the statement in a separate portion 
     # taking care to re-collapse any breaks caused by additional colons 
     out <- data.frame(speaker = x[1] 
          , text = paste(x[-1], collapse = ":")) 
     } else{ 
     # If not a legit speaker, set speaker to NA and reset text as above 
     out <- data.frame(speaker = NA 
          , text = paste(x, collapse = ":")) 
     } 
     # Return whichever version we made above 
     return(out) 
    }) %>% 
    # Bind all of the rows together 
    bind_rows %>% 
    # Identify clusters of speech that go with a single speaker 
    mutate(speakingGroup = cumsum(!is.na(speaker))) %>% 
    # Group by those clusters 
    group_by(speakingGroup) %>% 
    # Collapse that speaking down into a single row 
    summarise(speaker = speaker[1] 
       , fullText = paste(text, collapse = "\n")) 
}) 

Daje

[[1]] 

speakingGroup speaker                fullText                                                           

      1 President Dr. Norbert Lammert           I declare the session open.\nI will now give the floor to Bundesminister Alexander Dobrindt.                                      
      2 Alexander Dobrindt, Minister for Transport and Digital Infrastructure Ladies and Gentleman. We will today start the biggest investment in infrastructure that ever existed, with over 270 billion Euro, over 1 000 projects and a clear financing perspective.\nThis sentence right here: it is an example of a problem 

Jeśli wolisz, aby każdy wiersz tekstu osobno wymienić summarise na koniec z mutate(speaker = speaker[1]) a wami otrzyma jedną linię dla każdego wiersza mowy, tak jak to:

speaker                text                                              speakingGroup 
President Dr. Norbert Lammert           I declare the session open.                                           1 
President Dr. Norbert Lammert           I will now give the floor to Bundesminister Alexander Dobrindt.                                  1 
Alexander Dobrindt, Minister for Transport and Digital Infrastructure                                                  2 
Alexander Dobrindt, Minister for Transport and Digital Infrastructure Ladies and Gentleman. We will today start the biggest investment in infrastructure that ever existed, with over 270 billion Euro, over 1 000 projects and a clear financing perspective.    2 
Alexander Dobrindt, Minister for Transport and Digital Infrastructure This sentence right here: it is an example of a problem                                    2 
+0

Dziękuję, to świetnie! prawdopodobnie będę mieć pytanie lub dwa, gdy nie mam pracy - dziękuję za pomoc! – erocoar

2

Oto podejście:

 require (qdap) 
     #text is the document text 

     # remove round brackets and text b/w() 
     a <- bracketX(text, "round") 

     names <- c("President Dr. Norbert Lammert","Alexander Dobrindt") 
     searchString <- paste(names[1],names[2], sep = ".+") 

     # Get string from names[1] till names[2] with the help of searchString 
     string <- regmatches(a, regexpr(searchString, a)) 

     # remove names[2] from string 
     string <- gsub(names[2],"",string) 

Ten kod może być zapętlony, gdy istnieje więcej niż 2 nazwy

+0

Dziękuję za pomoc! Niestety, jeśli mam wiele dokumentów i więcej nazw, nie mogę zastosować do nich wszystkich możliwych zamówień (?), Czy wiesz, jak mogę to zrobić? – erocoar

+0

Moim zdaniem, jest to jedyny sposób, o ile nie istnieje stały separator/symbol po skrypcie każdego głośnika. jeśli "(" użyte po skrypcie każdego głośnika, możesz uzyskać cały tekst przed tym symbolem, a następnie uruchomić go po nazwie każdego z głośników, aby zobaczyć, o kim wspomniano. " – Sourabh

1

To wydaje się działać

library(qdap) 

members <- c("Alexander Dobrindt, Minister for Transport and Digital Infrastructure:","President Dr. Norbert Lammert:") 
members_r <- c("@Alexander Dobrindt, Minister for Transport and Digital Infrastructure:","@President Dr. Norbert Lammert:") 

testprok <- read.table("txt",header=FALSE,quote = "\"",comment.char="",sep="\t") 

testprok$V1 <- mgsub(members,members_r,testprok$V1) 

testprok$V2 <- ifelse(grepl("@[^\\@:]*:",testprok$V1),testprok$V1,NA)  

####function from http://stackoverflow.com/questions/7735647/replacing-nas-with-latest-non-na-value   
repeat.before = function(x) { # repeats the last non NA value. Keeps leading NA 
    ind = which(!is.na(x))  # get positions of nonmissing values 
    if(is.na(x[1]))    # if it begins with a missing, add the 
    ind = c(1,ind)  # first position to the indices 
    rep(x[ind], times = diff( # repeat the values at these indices 
    c(ind, length(x) + 1))) # diffing the indices + length yields how often 
}        # they need to be repeated 

testprok$V2 = repeat.before(testprok$V2)