Como tira cabeçalhos / rodapés de textos Project Gutenberg?
-
13-09-2019 - |
Pergunta
Eu tentei vários métodos para tirar a licença a partir de textos do Projeto Gutenberg, para uso como um corpus para um projeto de aprendizagem de línguas, mas eu não consigo chegar a uma abordagem sem supervisão, confiável. A melhor heurística eu vim acima com a medida está descascando os primeiros vinte e oito linhas e o último 398, que trabalhavam para um grande número de textos. Quaisquer sugestões sobre maneiras que eu posso tira automaticamente o texto (que é muito semelhante para os lotes dos textos, mas com ligeiras diferenças em cada caso, e alguns modelos diferentes, bem), bem como sugestões de como verificar se o texto tem sido despojado com precisão, seria muito útil.
Solução
Você não estava brincando. É quase como se eles estavam tentando fazer o trabalho AI-completo. Não consigo pensar em apenas duas abordagens, nenhum deles aperfeiçoar.
1) Configure um script em, digamos, Perl, para enfrentar os padrões mais comuns (por exemplo, olhar para a frase "produzido por", continue indo para baixo para a próxima linha em branco e corte lá), mas colocar em lotes de afirmações sobre o que é esperado (por exemplo, o próximo texto deve ser o título ou autor). Dessa forma, quando o padrão falhar, você vai saber. A primeira vez que um padrão falhar, fazê-lo com a mão. O segundo tempo, modificar o script.
2) Tente Mechanical Turk da Amazon .
Outras dicas
Eu também queria uma ferramenta para retirar cabeçalhos e rodapés Project Gutenberg por anos para jogar com o processamento da linguagem natural sem contaminar a análise com clichê misturado com o etxt. Depois de ler esta pergunta eu finalmente puxou meu dedo e escreveu um filtro Perl que você pode canalizar através em qualquer outra ferramenta.
É feito como uma máquina de estado usando expressões regulares por linha. Ele é escrito para ser fácil de entender já que a velocidade não é um problema com o tamanho típico de textos electrónicos. Até agora ele funciona sobre o casal dúzia de textos electrónicos que tenho aqui, mas na selva há a certeza de haver muitos mais variações que precisam ser adicionados. Esperemos que o código é bastante claro que qualquer um pode adicionar a ele:
#!/usr/bin/perl
# stripgutenberg.pl < in.txt > out.txt
#
# designed for piping
# Written by Andrew Dunbar (hippietrail), released into the public domain, Dec 2010
use strict;
my $debug = 0;
my $state = 'beginning';
my $print = 0;
my $printed = 0;
while (1) {
$_ = <>;
last unless $_;
# strip UTF-8 BOM
if ($. == 1 && index($_, "\xef\xbb\xbf") == 0) {
$_ = substr($_, 3);
}
if ($state eq 'beginning') {
if (/^(The Project Gutenberg [Ee]Book( of|,)|Project Gutenberg's )/) {
$state = 'normal pg header';
$debug && print "state: beginning -> normal pg header\n";
$print = 0;
} elsif (/^$/) {
$state = 'beginning blanks';
$debug && print "state: beginning -> beginning blanks\n";
} else {
die "unrecognized beginning: $_";
}
} elsif ($state eq 'normal pg header') {
if (/^\*\*\*\ ?START OF TH(IS|E) PROJECT GUTENBERG EBOOK,? /) {
$state = 'end of normal header';
$debug && print "state: normal pg header -> end of normal pg header\n";
} else {
# body of normal pg header
}
} elsif ($state eq 'end of normal header') {
if (/^(Produced by|Transcribed from)/) {
$state = 'post header';
$debug && print "state: end of normal pg header -> post header\n";
} elsif (/^$/) {
# blank lines
} else {
$state = 'etext body';
$debug && print "state: end of normal header -> etext body\n";
$print = 1;
}
} elsif ($state eq 'post header') {
if (/^$/) {
$state = 'blanks after post header';
$debug && print "state: post header -> blanks after post header\n";
} else {
# multiline Produced / Transcribed
}
} elsif ($state eq 'blanks after post header') {
if (/^$/) {
# more blank lines
} else {
$state = 'etext body';
$debug && print "state: blanks after post header -> etext body\n";
$print = 1;
}
} elsif ($state eq 'beginning blanks') {
if (/<!-- #INCLUDE virtual=\"\/include\/ga-books-texth\.html\" -->/) {
$state = 'header include';
$debug && print "state: beginning blanks -> header include\n";
} elsif (/^Title: /) {
$state = 'aus header';
$debug && print "state: beginning blanks -> aus header\n";
} elsif (/^$/) {
# more blanks
} else {
die "unexpected stuff after beginning blanks: $_";
}
} elsif ($state eq 'header include') {
if (/^$/) {
# blanks after header include
} else {
$state = 'aus header';
$debug && print "state: header include -> aus header\n";
}
} elsif ($state eq 'aus header') {
if (/^To contact Project Gutenberg of Australia go to http:\/\/gutenberg\.net\.au$/) {
$state = 'end of aus header';
$debug && print "state: aus header -> end of aus header\n";
} elsif (/^A Project Gutenberg of Australia eBook$/) {
$state = 'end of aus header';
$debug && print "state: aus header -> end of aus header\n";
}
} elsif ($state eq 'end of aus header') {
if (/^((Title|Author): .*)?$/) {
# title, author, or blank line
} else {
$state = 'etext body';
$debug && print "state: end of aus header -> etext body\n";
$print = 1;
}
} elsif ($state eq 'etext body') {
# here's the stuff
if (/^<!-- #INCLUDE virtual="\/include\/ga-books-textf\.html" -->$/) {
$state = 'footer';
$debug && print "state: etext body -> footer\n";
$print = 0;
} elsif (/^(\*\*\* ?)?end of (the )?project/i) {
$state = 'footer';
$debug && print "state: etext body -> footer\n";
$print = 0;
}
} elsif ($state eq 'footer') {
# nothing more of interest
} else {
die "unknown state '$state'";
}
if ($print) {
print;
++$printed;
} else {
$debug && print "## $_";
}
}
Uau, esta questão é tão velho agora. No entanto, o pacote gutenbergr em R parece estar a fazer um trabalho ok de remover cabeçalhos, incluindo lixo após o término 'oficial' do cabeçalho.
Primeiro você vai precisar instalar R / rstudio, então
install.packages('gutenbergr')
library(gutenbergr)
t <- gutenberg_download('25519') # give it the id number of the text
Os strip_headers arg é T por padrão. Você também provavelmente vai querer remover ilustrações:
library(data.table)
t <- as.data.table(t) # I hate tibbles -- datatables are easier to work with
head(t) # get the column names
# filter out lines that are illustrations and joins all lines with a space
# the \\[ searches for the [ character, the \\ are used to 'escape' the special [ character
# the !like() means find rows where the text column is not like the search string
no_il <- t[!like(text, '\\[Illustration'), 'text']
# collapse the text into a single character string
t_cln <- do.call(paste, c(no_il, collapse = ' '))