繁体   English   中英

在python中切片unicode字符串的正确方法是什么?

[英]What is the correct way to slice a unicode string in python?

我是python的新手,正在玩那些爬网的爬虫。 我想抓住描述字符串的前10个字符并将其用作标题

以下python代码片段产生以下JSON

item['image'] = img.xpath('@src').extract()
item_desc = img.xpath('@title').extract()
print(item_desc)
item['description'] = item_desc
item['title'] = item_desc[:10]
item['parentUrl'] = response.url

{'description': [u'CHAR-BROIL Tru-Infrared 350 IR Gas Grill - SportsAuthority.com '],
 'image': [u'http://www.sportsauthority.com/graphics/product_images/pTSA-10854895t130.jpg'],
 'parentUrl': 'http://www.sportsauthority.com/category/index.jsp?categoryId=3077576&clickid=topnav_Jerseys+%26+Fan+Shop',
 'title': [u'CHAR-BROIL Tru-Infrared 350 IR Gas Grill - SportsAuthority.com ']}

我想要的是下面的内容。 切片的行为不符合ID的预期。

{'description': [u'CHAR-BROIL Tru-Infrared 350 IR Gas Grill - SportsAuthority.com '],
 'image': [u'http://www.sportsauthority.com/graphics/product_images/pTSA-10854895t130.jpg'],
 'parentUrl': 'http://www.sportsauthority.com/category/index.jsp?categoryId=3077576&clickid=topnav_Jerseys+%26+Fan+Shop',
 'title': [u'CHAR-BROIL']}

item_desc是其中包含一个元素的列表 ,并且该元素是unicode字符串。 它本身不是unicode字符串。 [...]是一个很大的提示出现。

取出元素,切片,然后将其放回列表中:

item['title'] = [item_desc[0][:10]]

显然, .extract()函数可以返回多个匹配项; 如果您只期望一场比赛,也可以选择第一个:

item['image'] = img.xpath('@src').extract()[0]
item_desc = img.xpath('@title').extract()[0]
item['description'] = item_desc
item['title'] = item_desc[:10]

如果您的XPath查询并非总是返回结果,请首先测试一个空列表:

img_match = img.xpath('@src').extract()
item['image'] = img_match[0] if img_match else ''
item_desc = img.xpath('@title').extract()
item['description'] = item_desc[0] if item_desc else ''
item['title'] = item_desc[0][:10] if item_desc else ''

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM