簡體   English   中英

在 python 中將字符串分成數字和字母

[英]Separating a string into numbers and letters in python

兩天前開始學習python。 今天我構建了一個 web 抓取腳本,它從 yahoo Finance 中提取數據並將其放入 csv 文件中。 我遇到的問題是某些值是字符串,因為雅虎財經如此顯示它們。

例如:收入:806.43M

當我將它們復制到 csv 時,我無法使用它們進行計算,所以我想知道是否可以將“806.43”和“M”分開,同時仍然保持兩者查看數字的單位並將它們放在兩個不同的列中。

對於 excel 寫作我使用這個命令:

f.write(revenue + "," + revenue_value + "\n")

在哪里:

print(revenue)
Revenue (ttm)
print(revenue_value)
806.43M

所以最后我應該能夠使用一個看起來像這樣的命令

f.write(revenue + "," + revenue_value + "," + revenue_unit + "\n")

其中收入值是 806.43,收入單位是 M

希望有人可以幫助解決這個問題。

我相信最簡單的方法是將數字解析為字符串,然后根據字符串末尾的單位將其轉換為浮點數。


以下應該可以解決問題:

def parse_number(number_str) -> float:
    mapping = {
        "K": 1000,
        "M": 1000000,
        "B": 1000000000
    }

    unit = number_str[-1]
    number_float = float(number_str[:-1])

    return number_float * mapping[unit]

這是一個例子:

my_number = "806.43M"
print(parse_number(my_number))
>>> 806430000.0

您可以隨時嘗試正則表達式

這是一個很好的在線工具,可讓您練習使用 Python 特定的標准。

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()

Output:

{'category': 'Revenue (ttm)',
'value': '806.43',
'unit': 'M'}

我們還可以使用 .groups() 以元組的形式列出結果。

res.groups()

Output:

('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()

我們將使用花哨的 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")')

Output:

f.write(revenue + "," + revenue_value + "," + revenue_unit + "\n")

f.write("Revenue (ttm)" + "," + "806.43" + "," + "M" + "\n")

暫無
暫無

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

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