-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextract_text_from_epub.pl
More file actions
49 lines (36 loc) · 956 Bytes
/
extract_text_from_epub.pl
File metadata and controls
49 lines (36 loc) · 956 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/perl
use 5.014;
use HTML::TagParser;
use File::Temp qw(tempdir);
use File::Basename;
my ($file, $text_file) = @ARGV;
if (not defined $file or $file !~ /epub$/) {
say "Usage: $0 file.epub [output]";
exit 1;
}
if (not defined $text_file) {
my ($name, $path, $suffix) = fileparse($file, '.epub');
$text_file = "$name.txt";
}
if (not -e $file) {
say "file: $file not existed.";
exit 2;
}
my $tmp_dir = tempdir( CLEANUP => 1);
`unzip $file -d $tmp_dir`;
my @htmls = glob("$tmp_dir/OEBPS/Text/*xhtml");
open my $fh, '>', $text_file
or die "Can't open $text_file: $!";
for my $page (
sort {
my ($a_num) = $a =~ /s(\d+)\.xhtml/;
my ($b_num) = $b =~ /s(\d+)\.xhtml/;
$a_num <=> $b_num;
} @htmls) {
my $html = HTML::TagParser->new( $page );
for my $div ( $html->getElementsByTagName('div') ) {
my $text = $div->innerText;
print $fh $text;
}
}
close $fh;