1

我有一个字符串,

data = 'very <strong class="keyword">Awesome</strong> <strong class="keyword">Book</strong> discount'

我想将列表中的输出作为

ans = ['very','<strong class="keyword">Awesome</strong>','<strong class="keyword">Book</strong>','discount']

所以我可以知道单词的位置以及标签中出现的单词。我使用 BeautifulSoup 提取单词 in 和单词 with are not in 。但我需要找到位置。我试过的代码。

from bs4 import BeautifulSoup as BS
data = 'very <strong class="keyword">Awesome</strong> <strong class="keyword">Book</strong>'
soup = BS(data)
to_extract = soup.findAll('strong')
[comment.extract() for comment in to_extract]
soup = str(soup)
notInStrongWords = []
for t in to_extract:
    t_soup = BS('{0}'.format(t))
    t_tag = t_soup.strong
    matchWords.append(t_tag.string)
soup = re.sub("[^A-Za-z0-9\\-\\.\\(\\)\\\\\/\\&': ]+",' ', soup)
soup = re.findall('[(][^)]*[)]|\S+', soup)
InStrongWords = []
InStrongWords = [x for x in soup]

提前致谢。

4

3 回答 3

1

尝试(对于 Python 2.x - Python 3 的 unicode 不同):

from bs4 import BeautifulSoup as BS
data = 'very <strong class="keyword">Awesome</strong> <strong class="keyword">Book</strong>'
soup = BS(data)
pTag = soup.p
list = [ unicode(child) for child in pTag.children ]
print list

回报:

[u'very ', u'<strong class="keyword">Awesome</strong>', u' ', u'<strong class="keyword">Book</strong>']

基本上,迭代子元素并将它们转换回 Unicode 字符串。您可能想要过滤掉空格,但这在技术上存在于您的 HTML 中。

如果您需要检查哪些孩子“强壮”,您可以执行以下操作:

import bs4

data = 'very <strong class="keyword">Awesome</strong> <strong class="keyword">Book</strong>'
soup = bs4.BeautifulSoup(data)

list = [ (child.name if isinstance(child, bs4.Tag) else None, unicode(child)) for child in soup.children ]
print list

它返回一个元组列表,每个元组是(标签的名称或标签,HTML):

[(None, u'very '), (u'strong', u'<strong class="keyword">Awesome</strong>'), (None, u' '), (u'strong', u'<strong class="keyword">Book</strong>')]
于 2012-07-24T02:14:44.410 回答
1

根据 Andrew Alcok 的回答,谢谢 Ansrew。

可以说,

data = ['very <strong class="keyword">Awesome</strong> <strong class="keyword">Book</strong>','<strong class="keyword">Awesome</strong> <strong class="keyword">Book</strong> discount']

所以对于 python 2.x 和 BeautifulSoup 4

from bs4 import BeautifulSoup as BS
for d in data:
    soup = BS(d)
    soupPTag = soup.p
    if soupPTag:
        soupList = [unicode(child) for child in soupPTag.children if child!=" "]
        print soupList
    else:
        soupBodyTag = soup.body
        soupList = [unicode(child) for child in soupBodyTag.children if child!=" "]
        print soupList

这将给出所需的答案。

于 2012-07-24T19:38:22.960 回答
0

re.finditer(而不是re.findall) 为您提供匹配的对象,您可以获得start()and end()of。

于 2012-07-23T21:46:43.363 回答