如何使用perl将文本转换为XML?
输入文本文件包含以下内容:如何使用perl将文本转换为XML?,perl,Perl,输入文本文件包含以下内容: .... ponies B-pro were I-pro used I-pro A O report O of O indirect B-cd were O . O ... 输出XML文件 <sen> <base id="pro"> <w id="
....
ponies B-pro
were I-pro
used I-pro
A O
report O
of O
indirect B-cd
were O
. O
...
输出XML文件
<sen>
<base id="pro">
<w id="1">ponies</w>
<w id="2">were</w>
<w id="3">were</w>
</base>A report of
<base id="cd">indirect</base> were
</sen>
小马
是
是
报告
间接的
我想通过读取文本文件来创建一个XML文件,B-表示标记的开始,i-表示标记内包含单词,而“O”表示基本标记外,这意味着它只存在于标记中
我尝试以下代码:
#!/usr/local/bin/perl -w
open(my $f, "input.txt") or die "Can't";
open(my $o, ">output.xml") or die "Can't";
my $c;
sub read_line {
my $fh = shift;
if ($fh and my $line = <$fh>) {
chomp($line);
my @words = split(/\t/, $line);
my $word = $words[0];
my $group = $words[1];
if($word eq "."){
return;
}
else{
if($group ne 'O'){
my @b = split(/\-/, $group);
if($b[0] eq 'B'){
my $e = "<e id=\"";
$e .= " . $b[1] . "\">";
$e .= $word . "</e>";
return $e;
}
if($b[0] eq 'I'){
my $w = "<w id=\"";
$w .= $c . "\">";
$w .= $word . "</w>";
$c++;
return $w;
}
}
else{
$c = 2;
return $word;
}
}
}
return;
}
sub get_text(){
my $txt = "";
my $r = read_line($f);
while($r){
if($r =~ m/[[:punct:]]/){
chop($txt);
$txt .= " " . $r . " ";
}
else{
$txt .= $r . " ";
}
$r = read_line($f);
}
chop($txt);
return "<sen>" . $txt . ".</sen>";
}
#/usr/local/bin/perl-w
打开(my$f,“input.txt”)或死“不能”;
打开(我的$o,“>output.xml”)或死“不能”;
我的$c;
子读_行{
我的$fh=班次;
如果($fh和我的$line=){
chomp($line);
my@words=split(/\t/,$line);
我的$word=$words[0];
my$group=$words[1];
如果($word eq“){
返回;
}
否则{
如果($组ne'O'){
my@b=拆分(/\-/,$group);
如果($b[0]等式'b'){
my$e=“手工编写XML”只会给您带来麻烦。请使用中的模块
在您的例子中,我将首先将数据放在适当的Perl数据结构中(可能是包含一些数组或类似内容的哈希),然后使用模块(即XML::Simple for starters)输出到文件。正如Javs所说,您希望使用一个模块,而不是手工操作。出于您的目的,由于您有混合内容,我建议您使用。下面是一个我做的示例,以测试您是否确实可以使用混合内容,例如:
use XML::LibXML;
my $doc = XML::LibXML::Document->new();
my $root = $doc->createElement('html');
$doc->setDocumentElement($root);
my $body = $doc->createElement('body');
$root->appendChild($body);
my $link = $doc->createElement('a');
$link->setAttribute('href', 'http://google.com');
$link->appendText('Google');
$body->appendChild($link);
$body->appendText('Inline Text');
print $doc->toString;
不要试图通过将字符串组合在一起来生成XML。使用适当的XML模块。你的问题中有一大堆含糊不清的地方——间接
是否真的应该是
内部的文本而不是
?
ID只是全局递增?(XML禁止重用ID)。如果我们在blah B-bar
之后立即看到blah I-foo
(基本ID不匹配),会发生什么情况?我有一些工作代码,但如果没有这些问题的答案,我真的不能说它是正确的。展示给我看,也许我能得到一些想法。如果单词在第二列中有“O”,则只增加“B-”之后的下一个单词的“I-”,并重置为2。无论何时我发现“B-”,我都应该立即重置计数器。XML::Simple不会在这种情况下工作,因为输出包含混合内容。多谢,这真的很有帮助。您知道如何检测文本文件中的下一个单词是否具有i后缀或“O”。您可以尝试使用具有前瞻性的正则表达式。
use XML::LibXML;
my $doc = XML::LibXML::Document->new();
my $root = $doc->createElement('html');
$doc->setDocumentElement($root);
my $body = $doc->createElement('body');
$root->appendChild($body);
my $link = $doc->createElement('a');
$link->setAttribute('href', 'http://google.com');
$link->appendText('Google');
$body->appendChild($link);
$body->appendText('Inline Text');
print $doc->toString;