【问题标题】:Inserting integer data that has commas插入带逗号的整数数据
【发布时间】:2015-01-08 20:43:12
【问题描述】:

我正在尝试插入一大组(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] 调试:从 http://espn.go.com/nba/team/roster//name/mil/milwaukee-bucks> 抓取 {'年龄':你'21', '大学': u'LSU', '身高': u'6-9', 'name': u"Johnny O'Bryant III", '位置': u'PF', '薪水': u'$600,000', '重量': u'265'} 5,200,000 美元 2015-01-08 14:17:59-0500 [nbaStats] 调试:从 http://espn.go.com/nba/team/roster//name/mil/milwaukee-bucks> 抓取 {'年龄':你'30', '学院': u'\xa0', '身高': u'6-11', '名称': u'Zaza Pachulia', '位置': u'C', '薪水': u'$5,200,000', '重量': u'270'}

【问题讨论】:

  • 请贴一些代码。

标签: python mysql sqlite scrapy


【解决方案1】:

您可以更改您的 SQL 查询,以便在插入它们时从工资中删除逗号和美元符号。你可以通过改变来做到这一点

VALUES( ?, ?, ?, ?, ?, ?, ?)", \

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

这两个嵌套的REPLACE 操作删除了,$ 字符。

或者您可以更改您的 python 代码来删除多余的字符:

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

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

【讨论】:

  • 如果有两种不同的薪水,一种采用 $xxx,xxx 的形式,另一种采用 $xx,xxx,xxx 的形式,那么我需要使用 if 语句来检查薪水是否为第一次还是第二次?
  • 嘿Ollie,还有一个问题,我的身高以一种奇怪的格式显示,我应该如何格式化它们以按字符串插入? 437 个条目中有 40 个输入正确,但其他输入不正确。
  • 哦,我刚刚意识到所有 6-0 或 7-0 的条目都正确输入,作为字符串,但其他条目(基本上所有其他高度)显示为 5 位数字开头与 40xxx
猜你喜欢
  • 2011-05-12
  • 2014-12-18
  • 2014-02-09
  • 1970-01-01
  • 1970-01-01
  • 2019-07-05
  • 1970-01-01
  • 2018-04-14
  • 1970-01-01
相关资源
最近更新 更多