Skip to main content
 首页 » 编程设计

python之创建多个具有子节点的同名节点

2024年11月24日8落叶无声

我有一个文本文件,我用 python 使用 xml.etree.cElementTree 解析了它图书馆。 在输入中我有一段 <p>含句<s> , 每个句子都有单词 <w> ,这是文本文件的样子:

This 
is 
my 
first 
sentence. 
This 
is 
my 
second 
sentence. 

在输出中我想要以下 xml 文件:

<p> 
   <s> 
      <w>this</w> 
      <w>is</w> 
      <w>my</w> 
      <w>first</w> 
      <w>sentence</w> 
      <pc>.</pc> 
   </s> 
   <s> 
      <w>this</w> 
      <w>is</w> 
      <w>my</w> 
      <w>second</w> 
      <w>sentence</w> 
      <pc>.</pc> 
   </s> 
</p> 

我写了下面的 python 代码,给我段落标签和单词标签,我不知道如何实现有多个 <s> 的情况。标签。一个句子以大写字母开头,以点结尾。 我的 python 代码:

source_file = open("file.txt", "r") 
for line in source_file: 
    # catch ponctuation : . and , and ! and ? and () 
    if re.match("(\(|\)|\.|\,|\!)", str(line)): 
        ET.SubElement(p, "pc").text = line 
    else: 
        ET.SubElement(p, "w").text = line 
 
tree.write("my_file.xml", encoding="UTF-8", xml_declaration=True) 

以下 xml 输出:

<?xml version="1.0" encoding="UTF-8"?> 
<p> 
   <w>this</w> 
   <w>is</w> 
   <w>my</w> 
   <w>first</w> 
   <w>sentence</w> 
   <pc>.</pc> 
   <w>this</w> 
   <w>is</w> 
   <w>my</w> 
   <w>second</w> 
   <w>sentence</w> 
   <pc>.</pc> 
</p> 

我面临的问题是我无法创建新的 <s>为每个新句子添加标签,有没有办法使用 python 使用 xml 库来做到这一点?

请您参考如下方法:

基本上你需要一个逻辑来识别新句子。忽略明显的部分,应该像下面这样,

import os 
eos = False 
s = ET.SubElement(p, 's') 
for line in source_file: 
    line = str(line).rstrip(os.linesep) #to remove new line char at the end of each line 
    # catch ponctuation : . and , and ! and ? and () 
    if re.match("(\(|\)|\.|\,|\!)", line):   #don't think this matches 'sentence.', you will need to verify 
        ET.SubElement(s, "pc").text = line 
        eos = True 
    else: 
        if eos and line.strip() and line[0].isupper(): 
            s = ET.SubElement(p, 's') 
        eos = False 
        ET.SubElement(s, "w").text = line 

此外,您的正则表达式可能需要修复