简体   繁体   中英

How do you extract the floats from the elements in a python list?

I am using BeautifulSoup4 to build a script that does financial calculations. I have successfully extracted data to a list, but only need the float numbers from the elements.

For Example:

Volume = soup.find_all('td', {'class':'text-success'})

print (Volume)

This gives me the list output of:

[<td class="text-success">+1.3 LTC</td>, <td class="text- success">+5.49<span class="muteds">340788</span> LTC</td>, <td class="text-success">+1.3 LTC</td>,]

I want it to become:

[1.3, 5.49, 1.3]

How can I do this?

Thank-you so much for reading my post I greatly appreciate any help I can get.

You can find the first text node inside every td , split it by space, get the first item and convert it to float via float() - the + would be handled automatically:

from bs4 import BeautifulSoup

data = """
<table>
    <tr>
        <td class="text-success">+1.3 LTC</td>
        <td class="text-success">+5.49<span class="muteds">340788</span> LTC</td>
        <td class="text-success">+1.3 LTC</td>
    </tr>
</table>"""

soup = BeautifulSoup(data, "html.parser")

print([
    float(td.find(text=True).split(" ", 1)[0])
    for td in soup.find_all('td', {'class':'text-success'})
])

Prints [1.3, 5.49, 1.3] .

Note how the find(text=True) helps to avoid extracting the 340788 in the second td .

You can do

>>> import re
>>> re.findall("\d+\.\d+", yourString)
['1.3', '5.49', '1.3']
>>> 

Then to convert to floats

>>> [float(x) for x in re.findall("\d+\.\d+", yourString)]
[1.3, 5.49, 1.3]
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM