当前位置:网站首页>NLP中常用的utils
NLP中常用的utils
2022-07-28 05:22:00 【Alan and fish】
这是我在自己做实验中总结的一些工具方法,对于我这种菜鸟来说,经常不记得这些方法,可以拿出来使用使用.后续会持续更新.
1. 数据持久化成pkl格式\json格式,保存和获取pkl格式文件
- 导包
import pickle as pkl
import codecs
- 保存数据成pkl格式
def sava_pkl(path, obj, obj_name):
print(f'save {obj_name} in {path}')
with codecs.open(path, 'wb') as f:
pkl.dump(obj, f)
- 获取pkl格式数据
def load_pkl(path, obj_name):
print(f'load {obj_name} in {path}')
with codecs.open(path,'rb') as f:
data = pkl.load(f)
return data
- 将数据保存成JSON格式
def save_json(path,data):
# 先将字典对象转换成可读写的字符串
item=json.dumps(data,ensure_ascii=False,indent=2)
with open(path,"w",encoding='utf-8')as f:
f.write(item)
ensure_ascii默认是True,则就会将中文保存成十六进制格式
- 将数据处理成字典,然后再保存成JSON格式
for i in range(len(sen_lis)):
item = dict()
item["guid"] = i
item["text_a"] = sen_lis[i]
item["label"] = label_lis[i]
res.append(item)
print("all of %d instances" % (i + 1))
out_path=os.path.join(out_path,'ChnSenticrop'+index+'.json')
with open(out_path, "w",encoding='utf-8') as jfile:
json.dump(res, jfile, ensure_ascii=False)
2.读取CSV和JSON格式的数据
- 导包
import json
import csv
import codecs
- 读取CSV格式的数据
def load_csv(file):
data_list = []
with codecs.open(file, encoding='utf-8') as f:
reader = csv.DictReader(f)
for line in reader:
data = list(line.values())
data_list.append(data)
return data_list
- 读取JSON格式的数据
def load_json(file):
data_list = []
with codecs.open(file, encoding='utf-8') as f:
for line in f:
json_data = json.load(line)
data = list(json_data.values())
data_list.append(data)
return data_list
或者:
def load_json(file):
assert os.path.exists(file),'这个路径不存在'
data_list=[]
with codecs.open(file,encoding='utf-8')as f:
json_data=json.load(f)
for data in json_data:
data_list.append(data)
return data_list
###3.拼接成完整的路径,并且判断这个路径是否存在,如果不存在就创建路径
- 导包
import os
- 拼接路径,一般在保存文件的时候要用
data_path='data/out'
train_data_path=os.path.join(data_path,'triain.pkl')
if not os.path.exists(train_data_path):
os.makedirs(train_data_path)
4.tqdm和enumerate一起使用,可视化进度
from tqdm import tqdm
# 首先讲数据用tqdm包裹
epoch_iterator=tqdm(data_loader,desc='Iteration')
for batch_idx, batch in enumerate(epoch_iterator):
..............
注意导入包一定是:from tqdm import tqdm
5.读取文件路径
- 读取文件夹的一级目录
import os
dirs=os.listdir('-文件夹名称-')
- 读取多级目录
def get_Filelist(path):
for root, dirs, files in os.walk(path):
# root 表示当前正在访问的文件夹路径
# dirs 表示该文件夹下的子目录名list
# files 表示该文件夹下的文件list
print('root-dir',root)
print('sub-dirs',dirs)
print('files:',files)
print("=====================")
return dirs
6.同时打乱2个集合的顺序
def shuffle2list(a: list, b: list):
# shuffle two list with same rule, you can also use sklearn.utils.shuffle package
c = list(zip(a, b))
random.shuffle(c)
a[:], b[:] = zip(*c)
return a, b
7.lambda表达式
- lamdba表达式其实就是一种函数
例如:
def f(x):
return x*x
# 这个表达式就和上面的表示式是一个意思,其中第一个x表示函数的输入,冒号后面表示函数体
g=lambda x:x*x
print(g(5))输出的结果就是25
- lambda也可以输入两个数据
h=lambda x,y:x*y
print(h(5,4))输出的结果为20
- lambda还可以放在函数中使用
# 有的时候函数y=a*x*x+b*x+c,其中abc和x表示的意义不一样,这个时候就可以使用lambda表达式
def quadratic(a,b,c):
return lambda x:a*x*x+b*x+c
# 此时表示的就是a=1,b=-1,c=2的一元二次方程
f=quadratic(1,-1,2)
print(f(5))输出的结果为22
8.数据打包
- zip()函数
有三个list
test1=[“ccc”,“aaa”,“ddd”,“yyy”,“xxx”]
test2=(200,100,400,800,500)
test3=“daceb”
希望他们能列一起输出,即输出(“ccc”,200,d)这样的格式,这个时候就需要使用zip()函数将三个list封装到一起.见代码:
test1=["ccc","aaa","ddd","yyy","xxx"]
test2=(200,100,400,800,500)
test3="daceb"
feature=zip(test1,test2,test3)
for i in feature:
print(i)
输出结果:
('ccc', 200, 'd')
('aaa', 100, 'a')
('ddd', 400, 'c')
('yyy', 800, 'e')
('xxx', 500, 'b')
- 使用字典打包数据
有的时候要传递数据,如果数据比较多,不是很好传递到函数中,这个时候就可以使用字典打包数据,见代码:
test1=["ccc","aaa","ddd","yyy","xxx"]
test2=(200,100,400,800,500)
test3="daceb"
feature={'test1':test1,'test2':test2,'test3':test3}
# 这个时候就可以使用字典直接调用其中的数据
print(feature['test1'])
输出结果:
['ccc', 'aaa', 'ddd', 'yyy', 'xxx']
边栏推荐
- ModuleNotFoundError: No module named ‘pip‘
- 使用pycharm创建虚拟环境
- Addition, deletion and modification of data processing; constraint
- Micro service architecture cognition and service governance Eureka
- Invalid packaging for parent POM x, must be “pom“ but is “jar“ @
- 如何选择小程序开发企业
- MySQL multi table query
- uView上传组件upload上传auto-upload模式图片压缩
- 变量,流程控制与游标
- Distinguish between real-time data, offline data, streaming data and batch data
猜你喜欢

【四】redis持久化(RDB与AOF)

Use Python to encapsulate a tool class that sends mail regularly

Idempotent component
Sqoop安装及使用

分布式锁-Redis实现

Record the problems encountered in online capacity expansion server nochange: partition 1 is size 419428319. It cannot be grown

【2】 Redis basic commands and usage scenarios

数字藏品成文旅产业新热点

如何选择小程序开发企业

Data warehouse tool superset installation (fully available)
随机推荐
50 MySQL exercises + Answers
JS!!
7月7日国风廿四节气《小暑》来袭!!附..合..成..预..告..
mysql5.6(根据.ibd,.frm文件)恢复单表数据
KubeSphere安装版本问题
Chapter 8 aggregate function
微信团购小程序怎么做?一般要多少钱?
Mars数*字*藏*品*平*台守卫者计划细节公布
uView上传组件upload上传auto-upload模式图片压缩
Flink CDC (Mysql为例)
数字藏品以虚强实,赋能实体经济发展
MarsNFT :个人如何发行数字藏品?
Installation and use of sqoop
Micro service architecture cognition and service governance Eureka
撞脸ins? Mars数字藏品平台探索数字藏品轻社交
MySQL view, stored procedure and stored function
文旅头部结合数字藏品效应显著,但如何支撑用户持续购买力
At the moment of the epidemic, online and offline travelers are trapped. Can the digital collection be released?
xml解析实体工具类
小程序制作小程序开发适合哪些企业?