python文本数据处理——将数据处理成小程序数据库操作代码

困于心,衡于虑,而后作;征于色,发于声,而后喻。
内心忧困,思绪阻塞,然后才能有所作为。心绪显露在脸色上,表达在声音中,然后才能被人了解。
问题的背景是,在写小程序代码的时候,突然发现小程序数据库操作添加数据很麻烦,问题在哪里呢?因为部门人数几千人,一个个的加是很不现实的,必须使用小程序的数据库操作add方法,但是编辑代码也有几千行,问题就出在这里,如何获得这几千行代码将人员信息导入,从而最终实现小程序的登陆。
首先是将excel数据处理成txt格式,而且只要姓名和工号,读入excel,写入txt,这段代码部分涉及人员信息,所以不公布,但是思路是很简单的。
其次就是添加数据了,将数据读入,处理后写入新文件
下面给出代码

list = []
def wen_ben():
    # 首先处理123.txt里面的电气人员信息
    f = open("456.txt", "r")
    f2 = open("xie.txt", "w")
    line = f.readline().strip()
    f2.write("[" + "\"" + line + "\"" + "]" + ",")
    list.append(str(line))
    i = 0
    while line:
        i = i + 1
        print(line)
        line = f.readline().strip()
        f2.write("[" + "\"" + line + "\"" + "]" + ",")
        if i % 11 == 0:
            f2.write("\n")
        list.append(str(line))
    f.close()
    print("总数:" + str(i))
    f.close()
    f2.close()

def print_hi():
    # 再次处理文件,将数据写成JavaScript代码
    fo = open("foo.txt", "w")
    for i in range(0, 262, 2):
        # print(list[i])
        fo.write("{\n")
        fo.write("company:" + "\'" + "IWIP" + "\'" + "," + "\n")
        fo.write("department:" + "\'" + "电气设备部" + "\'" + "," + "\n")
        fo.write("id:" + "\'" + list[i+1] + "\'" + "," + "\n")
        fo.write("name:" + "\'" + list[i] + "\'" + "," + "\n")
        fo.write("openid:" + "\'" + "0000000000" + "\'" + "," + "\n")
        fo.write("password:" + "\'" + "000000" + "\'" + "," + "\n")
        fo.write("position:" + "\'" + "电工" + "\'" + "," + "\n")
        fo.write("telephone:" + "\'" + "123456789" + "\'" + "," + "\n")
        fo.write("},\n")
    fo.close()


if __name__ == '__main__':
    print("开始执行")
    wen_ben()
    print_hi()
    print("执行完毕")

小程序数据库操作代码中,将处理后的文本复制到数据中,改一下集合名,执行就可以完成添加数据了

db.collection('test')
  .add({
    data: [
      {
        _id: 'apple-1',
        name: 'apple',
        category: 'fruit',
        price: 10,
      },
      {
        _id: 'orange-1',
        name: 'orange',
        category: 'fruit',
        price: 15,
      },
    ]
  })

上一篇:《论语》文本分析


下一篇:GMOJ 6979.【2021.02.03冬令营模拟】天各一方(far)