Вы всегда можете попробовать регулярные выражения .
Вот довольно хороший онлайн-инструмент, позволяющий вам практиковаться в использовании Python -specifi c стандартов.
import re
sample = "Revenue (ttm): 806.43M"
# Note: the `(?P<name here>)` section is a named group. That way we can identify what we want to capture.
financials_pattern = r'''
(?P<category>.+?):?\s+? # Capture everything up until the colon
(?P<value>[\d\.]+) # Capture only numeric values and decimal points
(?P<unit>[\w]*)? # Capture a trailing unit type (M, MM, etc.)
'''
# Flags:
# re.I -> Ignore character case (upper vs lower)
# re.X -> Allows for 'verbose' pattern construction, as seen above
res = re.search(financials_pattern, sample, flags = re.I | re.X)
Распечатать наш словарь значений:
res.groupdict()
Вывод:
{'category': 'Revenue (ttm)',
'value': '806.43',
'unit': 'M'}
Мы также можем использовать .groups () для вывода результатов в кортеже.
res.groups()
Вывод:
('Revenue (ttm)', '806.43', 'M')
В этом случае мы сразу распаковываем эти результаты в имена переменных.
revenue = None # If this is None after trying to set it, don't print anything.
revenue, revenue_value, revenue_unit = res.groups()
Мы будем использовать fancy f -строки для распечатки вашего звонка f.write()
вместе с полученными результатами.
if revenue:
print(f'f.write(revenue + "," + revenue_value + "," + revenue_unit + "\\n")\n')
print(f'f.write("{revenue}" + "," + "{revenue_value}" + "," + "{revenue_unit}" + "\\n")')
Вывод:
f.write(revenue + "," + revenue_value + "," + revenue_unit + "\n")
f.write("Revenue (ttm)" + "," + "806.43" + "," + "M" + "\n")