本章主要讲述用Python造假数据
链接:https://mp.weixin.qq.com/s/Bx4ZP-SPPC_yDFJGYx0wiw
比较常用的数据的方法在这上面基本都有,如果没有想要的数据的话可自行百度查阅
# 自动化用faker造数据保存到txt
from faker import Faker
import pymysql
class Create_Data(object):
def __init__(self):
# 选择中文
fake = Faker("zh_CN")
# 生成数据改变循环体来控制数据量rang(?)
self.data_total = [
[fake.name(), fake.job(), fake.company(), fake.phone_number(), fake.company_email(), fake.address(),
fake.date_time(tzinfo=None)] for x in range(500)]
print(self.data_total)
# 写入txt
def deal_txt(self):
with open("D:\\AutoTest\\data_total.txt", "w", errors="ignore", encoding="utf-8") as output:
output.write("name, job, company, phone_number,company_email,address,date_time\n")
for row in self.data_total:
rowtxt = "{},{},{},{},{},{},{}".format(row[0], row[1], row[2], row[3], row[4], row[5], row[6])
output.write(rowtxt)
output.write("\n")
output.close()
print("Processing completed to txt")
if __name__ == '__main__':
data = Create_Data()
data.deal_txt()
# 自动化用faker造数据保存到excel
from faker import Faker
import pymysql
class Create_Data(object):
def __init__(self):
# 选择中文
fake = Faker("zh_CN")
# 生成数据改变循环体来控制数据量rang(?)
self.data_total = [
[fake.name(), fake.job(), fake.company(), fake.phone_number(), fake.company_email(), fake.address(),fake.date_time(tzinfo=None)] for x in range(100)]
print(self.data_total)
# 写入excel
def deal_excel(self):
df = pd.DataFrame(self.data_total,
columns=["name", "job", "company", "phone_number", "company_email", "address", "date_time"])
# 保存到本地excel
df.to_excel("D:\\AutoTest\\data_total.xlsx", index=False)
print("Processing completed to excel")
if __name__ == '__main__':
data = Create_Data()
data.deal_excel()
# 自动化导入数据到mysql数据库
from faker import Faker
import pymysql
class Create_Data(object):
def __init__(self):
# 选择中文
fake = Faker("zh_CN")
# 生成数据改变循环体来控制数据量rang(?)
self.data_total = [
[fake.name(), fake.job(), fake.company(), fake.phone_number(), fake.company_email(), fake.address(),
fake.date_time(tzinfo=None)] for x in range(100)]
print(self.data_total)
# 写入mysql
def deal_mysql(self):
# 打开数据库连接
db = pymysql.connect(host="localhost", port=3306, user="root",
password="123456",
db="bc_data_core",
charset="utf8")
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 插入语句
for val in self.data_total:
sql = "insert into faker_test(name,job,company,phone_number,company_email,address,date_time)value ('%s','%s','%s','%s','%s','%s','%s')" % (
val[0], val[1], val[2], val[3], val[4], val[5], val[6])
try:
# 执行sql语句
cursor.execute(sql)
# 执行sql语句
db.commit()
print("insert ok")
except:
# 发生错误时回滚
db.rollback()
# 关闭数据库连接
db.close()
if __name__ == '__main__':
data = Create_Data()
data.deal_mysql()