簡體   English   中英

如何在 python 中將從字符串中提取的數據的數據類型更改為貨幣或十進制

[英]How can I change the data type of data that is being extracted from string to money or decimal in python

我正在嘗試從網站中提取數據,我可以成功提取數據,但我面臨的挑戰是價格項目被存儲為字符串,我如何修改我的代碼以將價格存儲為十進制或我的 csv 文件中有錢嗎?

這是提取數據的圖像

def parse(self,response):
    count = 0
    for tv in response.xpath("//div[@class='products wrapper grid products-grid']/ol/li[@class='item product product-item']"):
        count +=1
        url = tv.xpath(".//div[@class='product-item-info']/div[@class='product details product-item-details']/strong/a/@href").get()
        name = tv.xpath(".//div[@class='product-item-info']/div[@class='product details product-item-details']/strong/a/text()").get()
        old_price = tv.xpath(".//div/span[@class='old-price']/span/span/span[@class='price']/text()").get()
        img = tv.xpath(".//div[@class='product-item-info']/a/span/span/img/@src").get()
        special_price = tv.xpath(".//div/span[@class='special-price']/span/span/span[@class='price']/text()").get()
        price = tv.xpath(".//div/div/span/span[@class='price-wrapper ']/span[@class='price']/text()").get()
   
               
        yield {
        'ID': count,
        'Name': name.strip() if name else name,
        'Description' : None,
        'Product_URL': url.strip() if url else url,
        'Old_Price': old_price.strip() if old_price else old_price, 
        'Special_Price' : special_price.strip()if special_price else special_price, 
        'Final_Price' : price.strip() if price else price,
        'Image_URL': img.strip() if img else img,
        'Category_ID' : 1
               

對於貨幣轉換,您可以嘗試以下操作:

from re import sub
from decimal import Decimal

str_value = 'R3,699.99'
numeric_value = Decimal(sub(r'[^\d.]', '', money))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM