Разбор речевых транскриптов с использованием R - PullRequest
0 голосов
/ 08 января 2019

У меня есть несколько больших транскриптов речей, которые я пытаюсь получить в формате фрейма данных, где каждая строка представляет речь / высказывание, а имя соответствующего оратора находится в столбце.

Вот снимок текста в его структурированном виде:

"sr. presidente domínguez.- "
" Tiene la palabra el señor diputado por Buenos Aires."
""
"sr. ATANASOF, ALFREDO NESTOR.- "
" Señor presidente: también quiero adherir en nombre del Frente Peronista a este homenaje al Gringo Soria. "
"   Me tocó compartir con él  muchos años de trabajo en esta Cámara y luego funciones en el Poder Ejecutivo nacional. Realmente, durante esos años pude descubrir los valores del Gringo: un gran militante y peronista, quien siempre anteponía la resolución de los temas a las situaciones de conflicto."
"   Hemos sentido mucho dolor cuando nos enteramos de esta desgraciada situación. Por ello, en nombre de nuestro bloque, quiero adherir al homenaje que hacemos a un amigo. Justamente, el Gringo Soria era un amigo para mí. (Aplausos.)"
""

Я использовал следующий цикл, чтобы попытаться проанализировать текст таким образом, чтобы каждая строка представляла говорящего и соответствующую речь / высказывание:

test <- readtext(text)
testtxt <- test$text

trans.prep <- function(testtxt) {

testtxt <- gsub("\\s{2,}", " ", testtxt, perl = T)
#gets rid of double spaces and replaces them with single spaces

testtxt <- subset(testtxt, nchar(testtxt) > 0)
#gets rid of lines that are empty (length of line is zero)

#collapse down to utterances

my.line <- 1

while (my.line <= length (testtxt)) {

  utterance <- length(grep(".-", testtxt[my.line], perl = T))
  if (utterance == 1) {my.line <- my.line + 1 }
  if (utterance == 0) {testtext[my.line-1] <-paste(testtext[(my.line-1):my.line], collapse = " ")
    testtext <- testtext[-my.line]} }
   testtxt <- subset(testtxt, nchar(testtxt) > 0)

  return(testtxt)}

Цикл должен возвращать проанализированный транскрипт, но когда я запускаю цикл, ничего не происходит, и R не выдает сообщение об ошибке.

Я новичок в разборе и все еще новичок в R, так что я уверен, что это часть моей проблемы. Любой совет будет принята с благодарностью.

Ответы [ 2 ]

0 голосов
/ 09 января 2019

Трудно точно определить, какой у вас формат ввода, поскольку пример воспроизводится не полностью, но давайте предположим, что ваш текст, напечатанный в вопросе, представляет собой строки из одного текстового файла. Здесь я сохранил его (без двойных кавычек) в виде текстового файла example.txt.

Мы разработали corpus_segment() для этого варианта использования.

library("quanteda")
## Package version: 1.3.14

example_corpus <- readtext::readtext("example.txt") %>%
  corpus()
summary(example_corpus)
## Corpus consisting of 1 document:
## 
##         Text Types Tokens Sentences
##  example.txt    93    141         8
## 
## Source: /private/var/folders/1v/ps2x_tvd0yg0lypdlshg_vwc0000gp/T/RtmpXk3YHc/reprex1325b73a1073d/* on x86_64 by kbenoit
## Created: Wed Jan  9 19:09:55 2019
## Notes:

example_corpus2 <-
  corpus_segment(example_corpus, pattern = "sr\\..*-", valuetype = "regex")
summary(example_corpus2)
## Corpus consisting of 2 documents:
## 
##           Text Types Tokens Sentences                        pattern
##  example.txt.1    10     10         1     sr. presidente domínguez.-
##  example.txt.2    80    117         7 sr. ATANASOF, ALFREDO NESTOR.-
## 
## Source: /private/var/folders/1v/ps2x_tvd0yg0lypdlshg_vwc0000gp/T/RtmpXk3YHc/reprex1325b73a1073d/* on x86_64 by kbenoit
## Created: Wed Jan  9 19:09:55 2019
## Notes: corpus_segment.corpus(example_corpus, pattern = "sr\\..*-", valuetype = "regex")

Мы можем немного привести в порядок.

# clean up pattern by removing unneeded elements
docvars(example_corpus2, "pattern") <-
  stringi::stri_replace_all_fixed(docvars(example_corpus2, "pattern"),
    c("sr. ", ".-"), "",
    vectorize_all = FALSE
  )

names(docvars(example_corpus2))[1] <- "speaker"

summary(example_corpus2)
## Corpus consisting of 2 documents:
## 
##           Text Types Tokens Sentences                  speaker
##  example.txt.1    10     10         1     presidente domínguez
##  example.txt.2    80    117         7 ATANASOF, ALFREDO NESTOR
## 
## Source: /private/var/folders/1v/ps2x_tvd0yg0lypdlshg_vwc0000gp/T/RtmpXk3YHc/reprex1325b73a1073d/* on x86_64 by kbenoit
## Created: Wed Jan  9 19:09:55 2019
## Notes: corpus_segment.corpus(example_corpus, pattern = "sr\\..*-", valuetype = "regex")
0 голосов
/ 08 января 2019

Проблема выглядит очень простой. Функция принимает переменную с именем testtxt. Тем не менее, в теле функции вы ссылаетесь на testtext (обратите внимание на дополнительный e). переменная, которую вы возвращаете, testtxt, не изменяется внутри функции. Чтобы поймать это в будущем, попробуйте начать с пустой рабочей области.

Ниже приведена функция, которая сработала для меня (вам нужно проверить, что результат соответствует ожидаемому).

> text <- c("sr. presidente domínguez.- ",
+           " Tiene la palabra el señor diputado por Buenos Aires.",
+           "",
+           "sr. ATANASOF, ALFREDO NESTOR.- ",
+           " Señor presidente: también quiero adherir en nombre del Frente Peronista a este homenaje al Gringo Soria. ",
+           "   Me tocó compartir con él  muchos años de trabajo en esta Cámara y luego funciones en el Poder Ejecutivo nacional. Realmente, durante esos años pude descubrir los valores del Gringo: un gran militante y peronista, quien siempre anteponía la resolución de los temas a las situaciones de conflicto.",
+           "   Hemos sentido mucho dolor cuando nos enteramos de esta desgraciada situación. Por ello, en nombre de nuestro bloque, quiero adherir al homenaje que hacemos a un amigo. Justamente, el Gringo Soria era un amigo para mí. (Aplausos.)",
+           "")
> 
> trans.prep <- function(testtxt) {
+   
+   testtxt <- gsub("\\s{2,}", " ", testtxt, perl = T)
+   #gets rid of double spaces and replaces them with single spaces
+   
+   testtxt <- subset(testtxt, nchar(testtxt) > 0)
+   #gets rid of lines that are empty (length of line is zero)
+   
+   #collapse down to utterances
+   
+   my.line <- 1
+   
+   while (my.line <= length (testtxt)) {
+     print(my.line)
+     
+     utterance <- length(grep(".-", testtxt[my.line], perl = T))
+     if (utterance == 1) {my.line <- my.line + 1 }
+     if (utterance == 0) {testtxt[my.line-1] <-paste(testtxt[(my.line-1):my.line], collapse = " ")
+     testtxt <- testtxt[-my.line]} }
+   testtxt <- subset(testtxt, nchar(testtxt) > 0)
+   
+   return(testtxt)}
> 
> k <- trans.prep(text)
[1] 1
[1] 2
[1] 2
[1] 3
[1] 3
[1] 3
> k
[1] "sr. presidente domínguez.-   Tiene la palabra el señor diputado por Buenos Aires."                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
[2] "sr. ATANASOF, ALFREDO NESTOR.-   Señor presidente: también quiero adherir en nombre del Frente Peronista a este homenaje al Gringo Soria.   Me tocó compartir con él muchos años de trabajo en esta Cámara y luego funciones en el Poder Ejecutivo nacional. Realmente, durante esos años pude descubrir los valores del Gringo: un gran militante y peronista, quien siempre anteponía la resolución de los temas a las situaciones de conflicto.  Hemos sentido mucho dolor cuando nos enteramos de esta desgraciada situación. Por ello, en nombre de nuestro bloque, quiero adherir al homenaje que hacemos a un amigo. Justamente, el Gringo Soria era un amigo para mí. (Aplausos.)"
...