2015-06-02 154 views
1

我使用網絡爬蟲來獲取一些數據。我將數據存儲在變量price中。類型的price是:Python:將unicode變量轉換爲字符串變量

<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) 

編輯2感謝Martin和馬蘇德我可以用str方法生成解決方案:

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

該方法返回一個int。這不是我原來的問題,但這是我項目的下一步。我添加了它,因爲我們不能將Unicode轉換成int,但首先使用encode()生成str

+0

你試過找bs4來串嗎?你很近。 – jamescampbell

+0

我試過'str(price)'然後'price.strip()',但它不起作用。 –

+0

你可以發佈你的bs4代碼嗎?你嘗試過str(價格[0])嗎? – jamescampbell

回答

2

使用正則表達式來從你的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字符串可以像普通字符串一樣工作。那就是u"500""500"差不多

+0

它看起來很優雅,但我不知道我是否可以將類型unicode的變量轉換爲字符串。 –

+1

在最後添加了一些額外的文本 - 是否有任何理由要轉換爲字符串? Unicode也是一個「字符串」。 –

+0

我知道。但是我不能在unicode「string」中使用字符串的方法,我想知道是否可以僅僅爲了知識而學習轉換。 –