Skip to content Skip to sidebar Skip to footer

Python Get Info From Long Complicated String

Im trying to get info from strings that I have parsed. Im trying to get the font size. This is the string Im returning style='fill: rgb(0, 0, 0); fill-opacity: 1; font-family: Proj

Solution 1:

You can use re module for the task:

style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: ProjectStocksFont; font-size: 70px; font-weight: normal; font-style: normal; text-decoration: none;"import re

print( re.search(r'font-size:\s*(\d+)', style)[1] )

Prints:

70

Solution 2:

Alternatively, you can parse the string to a dictionary. This might be useful if you want to access more than just that property.

style_dict = dict([[a.strip() for a in s.split(':')] for s in style.split(';') if s != ""])
style_dict['font-size']

Gives

'70px'

If you don't want the units:

style_dict['font-size'][:-2]

Solution 3:

Using the .split() method is one approach.

You can split the string into a python list to separate each kind of entry in your string. Then you can iterate though your list splitting each sub-string and save your values in a python dictionary.

style = "fill: rgb(0, 0, 0); fill-opacity: 1; font-family: ProjectStocksFont; font-size: 70px; font-weight: normal; font-style: normal; text-decoration: none;"
style_dict = {}
style = style.split("; ")

for item in style:
    key, value = item.split(": ")
    style_dict[key] = value

key = "font-size"
print(style_dict[key])

Solution 4:

You can use regular expressions to find what you need

importrestyle="fill:rgb(0,0,0);fill-opacity:1;font-family:ProjectStocksFont;font-size:70px;font-weight:normal;font-style:normal;text-decoration:none;"fontSize=re.findall("font-size:(.+)px",style)[0]# returns '70'

https://www.w3schools.com/python/python_regex.asp

Solution 5:

You can use a regex to accomplish this, but it would be better to use some package that understands CSS. Anyways, give this a try:

import re


style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: ProjectStocksFont; font-size: 70px; font-weight: normal; font-style: normal; text-decoration: none;"
font_size = re.match(r'.*font-size: ([^;^a-z]+).*', style)

Post a Comment for "Python Get Info From Long Complicated String"