首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用strip()删除空格

使用strip()删除空格
EN

Stack Overflow用户
提问于 2013-08-28 13:57:44
回答 2查看 10K关注 0票数 0

如何删除[u'\n\n\n result here \n\n\n']并获得仅作为[u'result here']的结果...我正在使用scrapy

代码语言:javascript
复制
def parse_items(self, response):
  str = ""
  hxs = HtmlXPathSelector(response)

  for titles in titles:
      item = CraigslistSampleItem()
      item ["job_id"] = (id.select('text()').extract() #ok
      items.append(item)
  return(items)
end

有谁可以帮我?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-08-28 14:14:46

代码语言:javascript
复制
id.select('text()').extract() 

返回包含文本的字符串列表。您应该遍历该列表以剥离每个项目,或者使用切片(例如your_list.strip() )来执行剥离空白。Strip方法实际上与字符串数据类型相关联。

代码语言:javascript
复制
def parse_items(self, response):
  str = ""
  hxs = HtmlXPathSelector(response)

  for titles in titles:
      item = CraigslistSampleItem()
      item ["job_id"] = id.select('text()').extract()[0].strip() #this should work if #there is some string data available. otherwise it will give an index out of range error.
      items.append(item)
  return(items)
end
票数 4
EN

Stack Overflow用户

发布于 2013-08-28 15:42:59

使用Python的 .strip()替代方案

您可以在选择“job_id”的XPath表达式周围使用XPath函数normalize-space()

代码语言:javascript
复制
def parse_items(self, response):
    hxs = HtmlXPathSelector(response)

    for titles in titles:
        item = CraigslistSampleItem()
        item ["job_id"] = title.select('normalize-space(.//td[@scope="row"])').extract()[0].strip()
        items.append(item)
    return(items)

注意1:我使用的XPath表达式是基于https://careers-cooperhealth.icims.com/jobs/search?ss=1&searchLocation=&searchCategory=&hashed=0

备注2在答案中使用 .strip()id.select('text()').extract()[0].strip()会得到u'result here',而不是列表。

这可能正是您所需要的,但是如果您想保留列表,因为您要求删除[u'\n\n\n result here \n\n\n']并获得[u'result here']形式的结果,那么您可以使用如下所示的内容,使用Python的map()

代码语言:javascript
复制
item ["job_id"] = map(unicode.strip, id.select('text()').extract())
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18480363

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档