Skip to main content
 首页 » 编程设计

python之将 HTML 中的播放翻译成 python

2025年05月04日14lautakyan007

所以,我想将莎士比亚的一部戏剧《哈姆雷特》表示为以下对象(也许这不是最好的表示,如果是请告诉我):

class Play(): 
  acts = [] 
  ... 
  def add_act(self, act): acts.append(act) 
 
class Act(): 
  scenes = [] 
  ... 
  def add_scene(self, scene): scenes.append(scene) 
 
class Scene(): 
  elems = [] 
  def __init__(self, title, setting=""): ... 
  def add_elem(self, elem): elems.append(elem) 
  ... 
 
class StageDirection(): # elem 
  def __init__(self, text): ... 
 
class Line(): # elem 
  def __init__(self, id, text, character = None): ... 
  # A None character represents a continuation from the previous line 
  # id could be, for example, 1.1.1 

当然,每个类中还有其他方法用于打印等。

问题是,如何从如下所示的 HTML 4 代码中获取基于这些类(或类似类)的结构:

<H3>ACT I</h3>  
<h3>SCENE I. Elsinore. A platform before the castle.</h3>  
<p><blockquote>  
<i>FRANCISCO at his post. Enter to him BERNARDO</i>  
</blockquote>  
 
<A NAME=speech1><b>BERNARDO</b></a>  
<blockquote>  
<A NAME=1.1.1>Who's there?</A><br>  
</blockquote>  
 
<A NAME=speech2><b>FRANCISCO</b></a>  
<blockquote>  
<A NAME=1.1.2>Nay, answer me: stand, and unfold yourself.</A><br>  
</blockquote>  
 
<A NAME=speech3><b>BERNARDO</b></a>  
<blockquote>  
<A NAME=1.1.3>Long live the king!</A><br>  
</blockquote>  
 
<A NAME=speech4><b>FRANCISCO</b></a>  
<blockquote>  
<A NAME=1.1.4>Bernardo?</A><br>  
</blockquote>  
 
<A NAME=speech5><b>BERNARDO</b></a>  
<blockquote>  
<A NAME=1.1.5>He.</A><br>  
</blockquote>  <!-- for more, see the source of shakespeare.mit.edu/hamlet/full.html --> 

把它翻译成这样:

play = Play() 
actI = Act() 
sceneI = Scene("Scene I", "Elsinore. A platform before the castle.") 
sceneI.add_elem(StageDirection("Francisco at his post. Enter to him Bernardo.")) 
sceneI.add_elem(Line("Bernardo", "Who's there?")) 
... 

当然,我不期望所有代码 — 但我应该使用哪些库,如果没有库,我应该使用逻辑吗?

谢谢。

(这是为了 future 的开源项目,我学习 Python 是为了好玩,而不是家庭作业。)

请您参考如下方法:

使用lxml 或类似的解析器。他们会将您的 HTML(XML?)读入文档树,这基本上是您编写的数据结构的更通用版本。

然后您可以遍历生成的树并修剪它或在内存中重建另一棵看起来像您想要的方式的树。但是 HTML -> 数据结构步骤是一个已解决的问题。


等等,您想生成实际的 Python 代码吗?你到底为什么想要那个?