0

我有一个字符串,其中包含以下方式的工资信息:

salaryMixed = "£25,000 - £30,000"

有时它看起来像这样:

salaryMixed = "EUR25,000 - EUR30,000"

其他时间是这样的:

salaryMixed = "£37.50 - £50.00"

我想要做的是删除除数值以外的所有字符,然后拆分这两个值,以便将它们放入各自的变量中,这些变量反映了低波段和高波段。到目前为止,我有:

if salaryMixed.find('£')!=-1: # found £ char
    salaryMixed = salaryMixed.replace("£", "")
if salaryMixed.find('-')!=-1: # found hyphen
    salaryMixed = salaryMixed.replace("-", "")
if salaryMixed.find(',')!=-1: # found comma
    salaryMixed = salaryMixed.replace(",", "")
if salaryMixed.find('EUR')!=-1: # found EUR
    salaryMixed = salaryMixed.replace("EUR", "")
salaryMixed = re.sub('\s{2,}', ' ', salaryMixed) # to remove multiple space

if len(salaryList) == 1:
    salaryLow = map(int, 0) in salaryList
    salaryHigh = 00000
else:
    salaryLow = int(salaryList.index(1))
    salaryHigh = int(salaryList.index(2))

salaryMixed但是我很困惑如何将这两个值分开,以及当不是年薪而是每小时的情况下如何处理小数点,salaryMixed = "£37.50 - £50.00"因为那不是浮点数吗?

我想稍后在代码中将此信息存储在 MySQL DB 中,但我已将该表描述为:

CREATE TABLE jobs(
   job_id INT NOT NULL AUTO_INCREMENT,
   job_title VARCHAR(300) NOT NULL,
   job_salary_low INT(25),
   job_salary_high INT(25),
   PRIMARY KEY ( job_id )
);

这里最好的方法是什么?谢谢。

4

3 回答 3

1

这是来自 python re 模块的正则表达式的一个很好的例子。而且您可能希望将每小时费率上调为年费率(假设您的平均每小时

import re

def salary_band(val):
    currency = 'EUR' if 'EUR' in val else 'GBP'
    numbers = re.findall("[0-9.\,]*", val) # this will have a bunch of empty entries and two numbers
    numbers = [i.replace(",","") for i in numbers if i] # filter out empty strings, remove commas
    numbers = map(float, numbers) # convert to floats
    annual = lambda p: int(p) if p > 2000 else int( p * 1800) # your number here...
    return currency, map(annual, numbers)

print salary_band ( "gbp37.50 - gbp50.00")
print salary_band ( "EUR25,000 - EUR30,000")
>> ('GBP', [75000, 100000])
>> ('EUR', [25000, 30000])

在这里,我将货币类型和高/低数字作为元组返回 - 您可以轻松地将其解压缩到您的表格中

于 2013-06-12T04:35:39.577 回答
1

我想要做的是删除除数值以外的所有字符,然后拆分这两个值,以便将它们放入各自的变量中,这些变量反映了低波段和高波段。到目前为止,我有:

好的,一次迈出这一步。删除除数值以外的所有字符(最好保留空格和句点)

>>> testcases =  ["£25,000 - £30,000", "EUR25,000 - EUR30,000", "£37.50 - £50.00"]
>>> res = [''.join(x for x in tc if x.isdigit() or x.isspace() or x == '.') for tc in testcases]
>>> res
['25000  30000', '25000  30000', '37.50  50.00']

好的,现在拆分它们

>>> res = [x.split() for x in res]
>>> res
[['25000', '30000'], ['25000', '30000'], ['37.50', '50.00']]

转换为浮点数(十进制可能更好)

>>> res = [[float(j) for j in i] for i in res]>>> res
[[25000.0, 30000.0], [25000.0, 30000.0], [37.5, 50.0]]

放入单独的变量

>>> for low, high in res:
...     print (low, high)
... 
25000.0 30000.0
25000.0 30000.0
37.5 50.0

@Patashu 建议的正则表达式是一种简单/懒惰的方法

于 2013-06-12T04:08:37.310 回答
0

为了将值存储在 db 中,您可以在 python 中使用 MySQLdb 库。它易于使用,并将您的所有数据存储到数据库中。在这里检查一下。

您可以通过 apt-get install python-mysqldb 安装它

于 2013-06-12T04:23:50.913 回答