簡體   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