2017-07-19 3 views
0

大きなテキストから文章を抽出したい。私のテキストはtihのようなものです -自由に流れるテキストからhtmlタグを削除して別の文章を作成する

<ul><li>Registered Nurse in <font>Missouri</font>, License number <font>xxxxxxxx</font>, <font>2017</font></li><li>AHA Advanced Cardiac Life Support (ACLS) Certification <font>2016-2018</font></li><li>AHA PALS - Pediatric Advanced Life Support 2017-2019</li><li>AHA Basic Life Support 2016-2018</li></ul> 

上記の文章から適切な文章を抽出したいと思います。だから、期待される出力は、私は上記のようなテキストからHTMLSを取り除くためにHTMLParserモジュール作り付けのpythonを使用し、リスト

['Registered Nurse in Missouri, License number xxxxxxxx, 2017', 
'AHA Advanced Cardiac Life Support (ACLS) Certification 2016-2018', 
'AHA PALS - Pediatric Advanced Life Support 2017-2019', 
'AHA Basic Life Support 2016-2018'] 

になります。ここに私のコードです。

class HTMLStripper(HTMLParser): 

    def __init__(self): 
     super().__init__() 
     self.reset() 
     self.strict = False 
     self.convert_charrefs= True 
     self.fed = [] 

    def handle_data(self, chunk): 
     #import pdb; pdb.set_trace() 
     self.fed.append(chunk.strip()) 

    def get_data(self): 
     return [x for x in self.fed if x] 


def strip_html_tags(html): 
    try: 
     s = HTMLStripper() 
     s.feed(html) 
     return s.get_data() 
    except Exception as e: 
     # Remove html strings from the given string 
     p = re.compile(r'<.*?>') 
     return p.sub('', html) 

それのように私は<ul> or <li> tagsに厳格なチェックを行うことはできません(それは現在の実装で生成する必要がありInfactは出力されます)上記のテキスト

['Registered Nurse in', 'Missouri', ', License number', 'xxxxxxx', ',', '2017', 'AHA Advanced Cardiac Life Support (ACLS) Certification', '2016-2018', 'AHA PALS - Pediatric Advanced Life Support 2017-2019', 'AHA Basic Life Support 2016-2018'] 

strip_html_tags関数を呼び出した上で次のような結果になります異なるテキストは異なるHTMLタグを持つことがあります。私は上記のようなテキストを外側のhtml-tagsに分割するのではなく、毎回分割するよりhtml-tagが発生しました

ありがとうございます。

+0

'[re.sub(R '<.*?>'、 '' html.splitの行のため、行)( '

  • ')]' – bakatrouble

  • 答えて

    1

    多くの審議の末、私はここで私のソリューションを投稿しています。私が持っていたさまざまな例ではかなりうまく動作します。 BeautifulSoupを使用するアプローチは、(私がsoup.findAll(specific_tag)を適用できるように)テキストを事前に抽出しなければならないタグ​​を知っていればうまくいくが、それは私には当てはまらない。また、私はテキストを抽出する必要があるから、複数のタグにすることができます。例えば ​​-

    <p>Science</p><div> Biology </div><div>Generation of mature T cells from human hematopoietic stem and progenitor cells in artificial thymic organoids. <span style=\"text-decoration: underline;\">Nature Methods</span> 2017,</div> 
    

    私は<p>タグと<div>タグの両方からテキストを抽出したい上の例。混合に十分

    [['ul'], ['li', 'li'], ['li', 'li'], ['li', 'li'], ['li', 'li'], ['ul']] 
    
    <ul><li>Registered Nurse in <font>Missouri</font>, License number <font>xxxxxxxx</font>, <font>2017</font></li><li>AHA Advanced Cardiac Life Support (ACLS) Certification <font>2016-2018</font></li><li>AHA PALS - Pediatric Advanced Life Support 2017-2019</li><li>AHA Basic Life Support 2016-2018</li></ul> 
    
    ['Registered Nurse in Missouri , License number xxxxxxxx , 2017', 'AHA Advanced Cardiac Life Support (ACLS) Certification 2016-2018', 'AHA PALS - Pediatric Advanced Life Support 2017-2019', 'AHA Basic Life Support 2016-2018'] 
    

    にも動作 -

    Iは、上記の例

    parser = HTMLStripper() 
    parser.feed(mystr) 
    l1 = parser.get_tree() 
    feed = parser.get_data() 
    print(l1) 
    print("\n", mystr) 
    print("\n", feed) 
    print("\n\n") 
    

    上のコードおよび出力を実行するようscenarios-

    import re 
    import copy 
    from html.parser import HTMLParser 
    from sample_htmls import * 
    
    class HTMLStripper(HTMLParser): 
    
        def __init__(self): 
         super().__init__() 
         self.reset() 
         self.strict = False 
         self.convert_charrefs= True 
         self.feeds = [] 
         self.sentence = '' 
         self.current_path = [] 
         self.tree = [] 
         self.lookup_tags = ['div', 'span', 'p', 'ul', 'li'] 
    
        def update_feed(self): 
         self.tree.append(copy.deepcopy(self.current_path)) 
         self.current_path[:] = [] 
         self.feeds.append(re.sub(' +', ' ', self.sentence).strip()) 
         self.sentence = '' 
    
        def handle_starttag(self, tag, attrs): 
         if tag in self.lookup_tags: 
          if tag == 'li' and len(self.current_path) > 0: 
           self.update_feed() 
          self.current_path.append(tag) 
    
        def handle_endtag(self, tag): 
         if tag in self.lookup_tags: 
          self.current_path.append(tag) 
          if tag == self.current_path[0]: 
           self.update_feed() 
    
        def handle_data(self, data): 
         self.sentence += ' ' + data 
    
        def get_tree(self): 
         return self.tree 
    
        def get_data(self): 
         return [x for x in self.feeds if x] 
    

    を処理するために上記のコードを変更しHTML文字列のタグ -

    [['p', 'p'], ['div', 'div'], ['div', 'span', 'span', 'div']] 
    
    <p>Science</p><div> Biology </div><div>Generation of mature T cells from human hematopoietic stem and progenitor cells in artificial thymic organoids. <span style="text-decoration: underline;">Nature Methods</span> 2017,</div> 
    
    ['Science', 'Biology', 'Generation of mature T cells from human hematopoietic stem and progenitor cells in artificial thymic organoids. Nature Methods 2017,'] 
    

    テキスト抽出ロジックを改善できるようにコーナーケースが大好きです。

    1

    htmlを効率的に解析できるツールを使用しないのはなぜですか? BeautifulSoupのように:だから今はこれ以上持っている

    text_without_tags = soup.text 
    

    from bs4 import BeautifulSoup 
    
    demo = '<ul><li>Registered Nurse in <font>Missouri</font>, License number <font>xxxxxxxx</font>, <font>2017</font></li><li>AHA Advanced Cardiac Life Support (ACLS) Certification <font>2016-2018</font></li><li>AHA PALS - Pediatric Advanced Life Support 2017-2019</li><li>AHA Basic Life Support 2016-2018</li></ul>' 
    soup = BeautifulSoup(demo, 'lxml') 
    sentences = [item.text for item in soup.findAll('li')] 
    

    変数sentencesは今、あなたが望んでいたまさに、私はこのコードを使用することになり、あなたのコメントの後にそれを自分

    をテスト保持していますあなたがコンマでsplit(',')のリストにすることができます(ただし、テキストが常にカンマやドットで表示されない場合は、文字列自体を使用するだけで気にしません)

    注:テキストの構造がわかっていないと、それを常に同じ方法で解析して既知の結果を得ることは不可能です。この既知の構造は、特定のhtmlタグでもあるかもしれませんが、あなたが事前に知っている特定のテキスト機能かもしれません。

    +0

    そのテキスト(この場合におけるLi)特定のタグを含んでいる必要はありません。また、テキストは整形式HTMLになる必要はありません。 –

    +0

    私の答えを更新しました –

    関連する問題