将列表中的字符串项转换为浮动

2024-05-20 02:44:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将列表中的最后一个“价格”项转换为实际的浮动,而不是输出中的字符串。这可能吗

输出

{'name': 'ADA Hi-Lo Power Plinth Table', 'product_ID': '55984', 'price': '$2,849.00'}
{'name': 'Adjustable Headrest Couch - Chrome-Plated Steel Legs', 'product_ID': '31350', 'price': '$729.00'}
{'name': 'Adjustable Headrest Couch - Chrome-Plated Steel Legs (X-Large)', 'product_ID': '31351', 'price': '$769.00'}
{'name': 'Adjustable Headrest Couch - Hardwood Base (No Drawers)', 'product_ID': '65446', 'price': '$1,059.00'}      
{'name': 'Adjustable Headrest Couch - Hardwood Base 2 Drawers', 'product_ID': '65448', 'price': '$1,195.00'}
{'name': 'Adjustable Headrest Couch - Hardwood Tapered Legs', 'product_ID': '31355', 'price': '$735.00'}
{'name': 'Adjustable Headrest Couch - Hardwood Tapered Legs (X-Large)', 'product_ID': '31356', 'price': '$775.00'}
{'name': 'Angeles Rest Standard Cot Sheets - ABC Print', 'product_ID': 'A31125', 'price': '$11.19'}

PYTHON脚本的开始

import requests
from bs4 import BeautifulSoup
import sys

with open('recoveryCouches','r') as html_file:
    content= html_file.read()
    soup = BeautifulSoup(content,'lxml')
    allProductDivs = soup.find('div', class_='product-items product-items-4')
    nameDiv = soup.find_all('div',class_='name')
    prodID = soup.find_all('span', id='product_id')
    prodCost = soup.find_all('span', class_='regular-price')

    records=[]
     
    for i in range(len(nameDiv)):
        records.append({
            "name": nameDiv[i].find('a').text.strip(),
            "product_ID": prodID[i].text.strip(),
            "price": prodCost[i].text.strip()
            })

    for x in records:
        print(x)

Tags: nameimportidallfindproductpriceclass
2条回答

简单地删除货币符号前缀会使代码不兼容i18n,而且很脆弱。general solution有点复杂,但是如果您假设货币符号仍然是前缀,并且是加元符号,那么:

from locale import setlocale, LC_ALL, localeconv, atof
from decimal import Decimal
import re

setlocale(LC_ALL, ('en_CA', 'UTF-8'))

# ...

price_str = re.sub(r'\s', '', prodCost[i].text)
stripped = price_str.removeprefix(localeconv()['currency_symbol'])
price = atof(stripped, Decimal)

还请注意Decimal在大多数情况下比float更能代表一种货币

您可以试试这个,因为您不能将$,都转换为float。您可以替换这两个选项,然后转换

您可以使用re模块立即替换它们:

import re

for i in range(len(nameDiv)):
    records.append({
        "name": nameDiv[i].find('a').text.strip(),
        "product_ID": prodID[i].text.strip(),
        "price": float(re.sub(r"[$,]","",prodCost[i].text.strip()))
            })

或者,如果所有字符串最初都有$,则可以跟随@Forest注释

float(price[1:].replace(',', ''))

像这样:

float(prodCost[i].text.strip()[1:].replace(",",""))

相关问题 更多 >