[英]Using Perl and Win32::OLE, how can I convert a numbered list in a Word document to plain text?
我編寫了一個Perl腳本來使用Win32 :: OLE讀取Microsoft Word文檔內容。
我的問題是包含編號列表的文檔(以1,2,3,...開頭)。 我的Perl腳本無法獲得該號碼。 我只能得到文字內容,而不是數字。
請建議如何將編號列表轉換為純文本,以保留編號和文本。
我的博客文章使用Perl和Win32 :: OLE從PowerPoint幻燈片中提取項目符號列表顯示了如何使用PowerPoint執行此操作。 事實證明Word的任務有點簡單。
#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
use Carp qw( croak );
use Const::Fast;
use Path::Class;
use Try::Tiny;
use Win32::OLE;
use Win32::OLE::Const ('Microsoft.Word');
use Win32::OLE::Enum;
$Win32::OLE::Warn = 3;
run(@ARGV);
sub run {
my $docfile = shift;
# Croaks if it cannot resolve
$docfile = file($docfile)->absolute->resolve;
my $word = get_word();
my $doc = $word->Documents->Open(
{
FileName => "$docfile",
ConfirmConversions => 0,
AddToRecentFiles => 0,
Revert => 0,
ReadOnly => 1,
}
);
my $pars = Win32::OLE::Enum->new($doc->Paragraphs);
while (my $par = $pars->Next) {
print_paragraph($par);
}
}
sub print_paragraph {
my $par = shift;
my $range = $par->Range;
my $fmt = $range->ListFormat;
my $bullet = $fmt->ListString;
my $text = $range->Text;
unless ($bullet) {
say $text;
return;
}
my $level = $fmt->ListLevelNumber;
say ">" x $level, join(' ', $bullet, $text);
return;
}
sub get_word {
my $word;
try { $word = Win32::OLE->GetActiveObject('Word.Application') }
catch { croak $_ };
return $word if $word;
$word = Win32::OLE->new('Word.Application', sub { $_[0]->Quit });
return $word if $word;
croak sprintf('Cannot start Word: %s', Win32::OLE->LastError);
}
鑒於以下Word文檔:
它生成輸出:
This is a document >1. This is a numbered list >2. Second item in the numbered list >3. Third one Back to normal paragraph. >>a. Another list >>b. Yup, here comes the second item >>c. Not so sure what to put here >>>i. Sub-item
對象瀏覽器是必不可少的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.