【问题标题】:Python: Transform a unicode variable into a string variablePython:将 unicode 变量转换为字符串变量
【发布时间】:2015-06-02 02:15:25
【问题描述】:

我使用网络爬虫来获取一些数据。我将数据存储在变量price 中。 price 的类型为:

<class 'bs4.element.NavigableString'>

price的每个元素的类型是:

<type 'unicode'>

基本上price 包含一些空格和换行符,后跟:$520。我想消除所有多余的符号,只恢复数字520。我已经做了一个天真的解决方案:

def reducePrice(price):
    key=0
    string=""
        for i in price:
            if (key==1):
                string=string+i
            if (i== '$'):
                key=1
    key=0
    return string

但我想实现一个更优雅的解决方案,将price 的类型转换为str,然后使用str 方法对其进行操作。我已经在网上和论坛的其他帖子中搜索了很多。我能得到的最好的结果是使用:

p = "".join(price)

我可以生成一个大的 unicode 变量。如果你能给我一个提示,我将不胜感激(我在 Ubuntu 中使用 python 2.7)。

编辑我添加我的蜘蛛以防万一你需要它:

def spider(max_pages):
        page = 1
        while page <= max_pages:
            url = "http://www.lider.cl/walmart/catalog/product/productDetails.jsp?cId=CF_Nivel2_000021&productId=PROD_5913&skuId=5913&pId=CF_Nivel1_000004&navAction=jump&navCount=12"
            source_code = requests.get(url)
            plain_text = source_code.text
            soup = BeautifulSoup(plain_text)
            title = ""
            price = ""
            for link in soup.findAll('span', {'itemprop': 'name'}):
                title = link.string
            for link in soup.find('em', {'class': 'oferLowPrice fixPriceOferUp  '}):
                price = link.string

            print(title + '='+ str(reducePrice(price)))
            page += 1

spider(1)

edit 2感谢 Martin 和 mASOUD,我可以使用 str 方法生成解决方案:

def reducePrice(price):
   return int((("".join(("".join(price)).split())).replace("$","")).encode())

这个方法返回一个int。这不是我最初的问题,但它是我项目的下一步。我添加它是因为我们无法将 unicode 转换为 int,但我们可以先使用 encode() 生成 str

【问题讨论】:

  • 您是否尝试过寻找 bs4 到字符串?你很接近。
  • 我尝试了str(price),然后尝试了price.strip(),但没有成功。
  • 你能发布你的bs4代码吗?你试过 str(price[0]) 吗?

标签: python unicode casting web-crawler unicode-string


【解决方案1】:

使用正则表达式从您的 Unicode 字符串中提取价格:

import re

def reducePrice(price):
    match = re.search(r'\d+', u'  $500  ')
    price = match.group()  # returns u"500"
    price = str(price) # convert "500" in unicode to single-byte characters.
    return price

尽管这个函数将 Unicode 转换为您所要求的“常规”字符串,但您有什么理由想要这个吗? Unicode 字符串可以像普通字符串一样使用。也就是u"500""500"几乎一样

【讨论】:

  • 它看起来很优雅,但我想知道我是否可以将 unicode 类型的变量转换为字符串。
  • 最后添加了一些额外的文本 - 你有什么理由要转换为字符串吗? Unicode 也是一个“字符串”。
  • 我知道。但是我不能在 unicode“字符串”中使用字符串的方法,我想知道是否可以为了知识而进行转换。
  • strip 绝对适用于 unicode 字符串。简单示例:u" 500 ".strip() 返回u"500"
  • 如果您真的只需要将 unicode 字符串转换为常规的“python2”字符串,您可以 encode() 它。比如:u'hi'.encode() 这会给你'hi'。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-24
  • 2022-08-11
  • 1970-01-01
  • 2010-09-30
相关资源
最近更新 更多