使用正则表达式从字符串中删除单词
我正在用Scrapy这个工具抓取一个网站,这个网站上有产品列表。我想做的是用正则表达式把产品标题中的一些不需要的词去掉。具体来说,我想去掉两个重复出现的词:笔和石墨铅笔,只保留品牌名称。
有没有什么建议呢?
<a name=“this-link”> href=“some url here”>Pen Bic Crystal</a>
some divs and other DOM structure
<a name=“this-link”> href=“some url here”>Graphite Pencil Kohinoor Carpenter</a>
some divs and other DOM structure
<a name=“this-link”> href=“some url here”>Pen Parker Jotter</a>
some divs and other DOM structure
<a name=“this-link”> href=“some url here”>Pen Bic Other Model</a>
some divs and other DOM structure
<a name=“this-link”> href=“some url here”>Graphite Pencil Palomino Blackwing Pearl</a>
1 个回答
4
Scrapy的选择器自带对正则表达式的支持。
在获取链接文本后,可以调用re()
:
sel.xpath('//a/text()').re(r'(?:Pen|Graphite Pencil)\s(.*)')
这里:
更新:
如果你只想获取Pen
或Graphite Pencil
后面的那个单词,可以使用这个正则表达式:r'(?:Pen|Graphite Pencil)\s(\w+)
,这样就只会捕获在Pen
或Graphite Pencil
和一个空格后面的字母数字(还有_
)字符。
使用scrapy shell
的示例:
$ scrapy shell index.html
>>> sel.xpath('//a/text()').re(r'(?:Pen|Graphite Pencil)\s(\w+)')
[u'Bic', u'Kohinoor', u'Parker', u'Bic', u'Palomino']