Repeat text extraction with Python

蹲街弑〆低调 提交于 2019-12-25 04:25:07

问题


I have the following code which I would like to use to extract texts information between <font color='#FF0000'> and </font>. It works fine but it only extracts one unit (the first one) whereas I would like to extract all textual units between these tags. I tried to do this with a bash loop code but it didn't work.

import os

directory_path ='C:\\My_folder\\tmp'

    for files in os.listdir(directory_path):

    print(files)

    path_for_files = os.path.join(directory_path, files)

    text = open(path_for_files, mode='r', encoding='utf-8').read()

    starting_tag = '<font color='
    ending_tag = '</font>'

    ground = text[text.find(starting_tag):text.find(ending_tag)]

    results_dir = 'C:\\My_folder\\tmp'
    results_file = files[:-4] + 'txt'

    path_for_files = os.path.join(results_dir, results_file)

    open(path_for_files, mode='w', encoding='UTF-8').write(result)

回答1:


You could use Beautiful Soup's css selectors.

>>> from bs4 import BeautifulSoup
>>> s = "foo <font color='#FF0000'> foobar </font> bar"
>>> soup = BeautifulSoup(s, 'lxml')
>>> for i in soup.select('font[color="#FF0000"]'):
    print(i.text)


 foobar 



回答2:


You can also use lxml.html 

>>> import lxml.html as PARSER
>>> s = "<html><body>foo <font color='#FF0000'> foobar </font> bar</body></html>"
>>> root = PARSER.fromstring(s)
>>> for i in root.getiterator("font"):
...   try: i.attrib["color"]
...   except:pass


来源:https://stackoverflow.com/questions/27619872/repeat-text-extraction-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!