【问题标题】:Exclude a tag (<pattern>) inside a tag (<topic>) on a result set using BeautifulSoup使用 BeautifulSoup 在结果集的标签 (<topic>) 内排除标签 (<pattern>)
【发布时间】:2018-08-09 01:06:04
【问题描述】:

我刚开始使用 Python 进行网络抓取,目前我正在使用 BeautifulSoup 进行数据提取。我有这个 .aiml 文件(xml),其中我想从标签 pattern 中提取所有数据,这些标签 NOT INCLUDEDtopic 标签内.

我已经获得了所有模式值,但这里的挑战是,那些具有 topic 父标记的模式不应包含在结果集中。

这里是目标文件:

<?xml version = "1.0" encoding = "UTF-8"?>

<aiml version="1.0.1" encoding="UTF-8">
  <topic name="botdog">
   <category>
      <pattern>MY DOG'S NAME IS *</pattern>
      <template>
         That is interesting that you have a dog named <set name="dog"><star/></set>
      </template>  
   </category>

   <category>
      <pattern>WHAT IS MY DOG'S NAME</pattern>
      <template>
         Your dog's name is <get name="dog"/>.
      </template>  
   </category>  
  </topic>

  <topic name="botcat">
   <category>
      <pattern>MY CAT'S NAME IS *</pattern>
      <template>
         That is interesting that you have a cat named <set name="cat"><star/></set>
      </template>  
   </category>

   <category>
      <pattern>WHAT IS MY CAT'S NAME</pattern>
      <template>
         Your cat's name is <get name="cat"/>.
      </template>  
   </category>  
  </topic>


  <category>
      <pattern>HELLO ALICE</pattern>
      <template>
         Hello User
      </template>
   </category>

   <category>
      <pattern>HOW ARE YOU</pattern>
      <template>
         I'm fine
      </template>
   </category>
</aiml>

Python 代码(Flask):

@extract.route('/')
def index_page():
    folder = 'templates/topic.aiml'
    with open(folder, 'r') as myfile:
        soup = BeautifulSoup(myfile.read(), 'html.parser')
    data_topic = [match.pattern.text for match in soup.find_all('category')]

    print(data_topic)


    # data = " ".join(data_set)

    return jsonify({'data_set': data_topic})

print() 的返回值为:

[“我的狗叫 *”、“我的狗叫什么”、“我的猫叫 *”、“我的猫叫什么”、“你好 ALICE”、“你好吗”]

应该只是这样,因为它没有父标签topic['HELLO ALICE', '你好吗']

【问题讨论】:

    标签: python beautifulsoup tags aiml


    【解决方案1】:

    试试这个:

    @extract.route('/')
    def index_page():
        folder = 'templates/topic.aiml'
    
        with open(folder, 'r') as myfile:
            soup = BeautifulSoup(myfile.read(), 'html.parser')
    
        data = []
        for cat in soup.find_all('category'):
            if cat.parent.name == "topic": continue
            data += [cat.find("pattern").text]
    
        print(data)
        return jsonify({'data_set': data})
    

    希望这会有所帮助!查看docs 了解更多示例。

    【讨论】:

    • 那是太棒了!谢啦! :) 在我看到你的答案之前,我所做的是: **for x in soup.find_all('topic'): x.extract() **,当然这是不合适的,因为我已经删除了标签。但是当我使用您的代码并打印汤时,它仍然存在,并且我得到了预期的结果集。 :) 再次感谢!
    • 很高兴我能帮忙,去打印更多汤 :)
    猜你喜欢
    • 2018-09-23
    • 2020-02-26
    • 2015-02-20
    • 2014-10-02
    • 2023-03-24
    • 2020-12-02
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    相关资源
    最近更新 更多