插入带逗号的整数数据

时间:2015-01-08 20:43:12

标签: python mysql sqlite scrapy

我正在尝试插入一大组(430个条目)的字典条目,其中一个键值对具有与之关联的工资,格式为$ xx,xxx,xxx。我如何解决这个问题,因为现在它将采用一个值并将其拆分为3列。

编辑:

def process_item(self, item, spider):
    if isinstance(item, TeamStats):
        for key, value in item.iteritems():
            if key == "division":
                print(item.get('division', ""))
                self.cur.execute("INSERT INTO Divs( division ) VALUES(?)", (item.get('division', ""),))
                self.con.commit() 

    if isinstance(item, Player):
        self.cur.execute("INSERT INTO Players(\
            player_name, \
            salary, \
            weight, \
            age, \
            height, \
            position, \
            college \
            ) \
            VALUES( ?, ?, ?, ?, ?, ?, ?)", \
            ( \
            item.get('name', ''),
            item.get('salary', 0),
            item.get('weight', 0),
            item.get('age', 0),
            item.get('height', ''),
            item.get('position', ''),
            item.get('college', '')
            ))

        self.con.commit() 
    return item

我插入管道的对象如下所示:

$ 600,000 2015-01-08 14:17:59-0500 [nbaStats]调试:从< 200 http://espn.go.com/nba/team/roster//name/mil/milwaukee-bucks >中删除     {'年龄':你'21',      '大学':u'LSU',      '身高':u'6-9',      'name':你是“Johnny O'Bryant III”,      '位置':u'PF',      '薪水':你'$ 600,000',      '重量':u'265'} $ 5,200,000 2015-01-08 14:17:59-0500 [nbaStats]调试:从< 200 http://espn.go.com/nba/team/roster/ /name/mil/milwaukee-bucks>中删除     {'年龄':你'30',      '大学':你'\ xa0',      '身高':u'6-11',      'name':u'Zaza Pachulia',      '位置':你'',      '薪水':你'$ 5,200,000',      '体重':u'270'}

1 个答案:

答案 0 :(得分:2)

您可以更改SQL查询,以便在插入工资时从工资中删除逗号和美元符号。你可以通过改变

来做到这一点
VALUES( ?, ?, ?, ?, ?, ?, ?)", \

VALUES( ?,    REPLACE(REPLACE(?,',',''),'$',''),   ?, ?, ?, ?, ?)", \

这两个嵌套的REPLACE操作会移除,$个字符。

或者您可以更改您的python代码以删除额外的字符:

        item.get('name', ''),
        re.sub(r'[,$]', "", item.get('salary', 0)),
        item.get('weight', 0),

无论哪种方式,都可以通过简单的字符串处理来清理带注释的数据。这两种方法都从数字字符串中删除所有美元符号和逗号。