0

以下是相关功能的代码:

def populateSubscribers(csvfile, db):
  conn = sqlite3.connect(db)
  conn.text_factory = str  #bugger 8-bit bytestrings
  cur = conn.cursor()

  subscriber_dict = {}

  # read values from tab-delimited csv file
  reader = csv.reader(open(csvfile, "rU"), delimiter = '\t')
  for Number, Name, Message, Datetime, Type in reader:
    if str(Number)[:1] == '1':
      tmpNumber = str(Number)[1:]
      Number = int(tmpNumber)

      # check to ensure name/number not null
      if Number and Name:
        # add unique subscribers to dictionary
        subscriber_dict[Number] = Name
      else:
        print 'Subscriber missing name or number'

  # insert unique subscribers into subscriber table
  for number, name in subscriber_dict.items():
    cur.execute('INSERT OR IGNORE INTO subscriber (name, phone_number) VALUES (?,?)', (name, number))
    conn.commit()

  cur.close()
  conn.close()
  print '...Successfully populated subcriber table.'

它从 csv 文件中读取订户姓名和电话号码,然后应该将每个唯一订户的条目写入数据库。我希望电话号码成为键/值对中的键,因为它是唯一的。但由于某种原因,它没有从数据中读取所有数字,它缺少一些订阅者。如果我将名称作为预期的键丢失(删除所有未知数),但作为键的电话号码完全丢失了一些数字。关于如何修复这里的逻辑的任何想法?

4

1 回答 1

1

在我看来if str(Number)[:1] == '1':可能是过滤掉了你的一些数据。

添加一个 else 并打印出它拒绝的任何内容。这些可能是出错的地方。

Either way, pare down your input data and find which one's aren't being used. Without seeing the data and the alternative you've said which does work, it's hard to pin down the exact cause here.

于 2012-06-12T23:14:56.620 回答