英文文本预处理的常见流程——Python代码实现

自然语言处理——中文文本预处理 自然语言处理——中文文本预处理 近期,在自学自然语言处理,初次接触NLP觉得十分的难,各种概念和算法,而且也没有很强的编程基础,学着稍微有点吃力。不过经过两个星期的学习,已经掌握了一些简单的中文、英文语料的预处理操作。写点笔记,记录一下学习的过程。 1、中文语料的特点 第一点:中文语料中词与词之间是紧密相连的,这一点不同与英文或者其它语种的语料,因此在分词的时候不能像英文使用空格分词,可以jieb... 阅读详情

目录

1.常见流程

2.导包

 3.定义函数:读取本地的数据集

4.定义函数:文本词元化 

5.定义函数:统计词元频率¶

 6.定义类:构建词汇表¶

 7.定义函数:整合所有的功能

 8.调用代码执行

1.常见流程

将文本作为字符串加载到内存中。

将字符串拆分为词元(如单词和字符)。

建立一个词汇表,将拆分的词元映射到数字索引。

将文本转换为数字索引序列,方便模型操作。

整合所有功能

 #知识点1:词汇表-->语料、<unk>、pad、bos、eos

1 <unk> :标记 未知词元

2  pad :若两句话长短不一致,补充pad使每一句话长度一致

3  bos :标记 句子开头标志

4  eos :标记 句子结尾标志

 #知识点2:

#知识点随记
#若是把一个英文的字符串放入列表中,是以char(一个字母一个字母)的形式放进去的
s = 'the time machine by h g wells'
list(s)
['t',
 'h',
 'e',
 ' ',
 't',
 'i',
 'm',
 'e',
 ' ',
 'm',
 'a',
 'c',
 'h',
 'i',
 'n',
 'e',
 ' ',
 'b',
 'y',
 ' ',
 'h',
 ' ',
 'g',
 ' ',
 'w',
 'e',
 'l',
 'l',
 's']

  #知识点3:

#dict().item()      返回字典的key和value

2.导包

#python自带的两个包
import collections    #该库提供了一些集合对象的实现,包括Counter、deque、defaultdict等
import re  #正则表达式的模块库

 3.定义函数:读取本地的数据集

def read_time_machine():
    with open('./article.txt', 'r') as f:  #'r'只读模式
        lines = f.readlines()  #读取每一行数据
    #re.sub参数:pattern表示正则表达式; repl:用什么替代;string:对什么文本操作; ^A-Za-z表示除了后面的A-Za-z,都要被替换;        +加号表示重复
    return [re.sub('[^A-Za-z]+', ' ',line).strip().lower() for line in lines] #不符合正则的用空格表示, strip():去掉空格, lower():把大写字母变成小写

4.定义函数:文本词元化 

def tokenize(lines, token='word'):   #token='word'相当于设置判断标志
    """将文本行拆分成单词或者字符词元
        lines:需要传入的数据
        token = 'word' 或者 token = 'char'两种形式
    """
    if token == 'word':
        #line.split()返回的是一个列表
        return [line.split() for line in lines]  #split()功能 默认按空格拆分数据
    elif token == 'char':
        #list(line) 返回的是一个列表
        return [list(line) for line in lines] #list(line)将一整行英文文本的字符串放入列表中,会每个字母单独成为一个列表元素
    else:     #若输入未知词元类型,打印报错提醒
        print('错误:未知词元类型:' + token)
#调用函数  #测试使用,无关代码
#总结:英文用token='char'进行词元化的较多,因为字母共有26个,word太多了
tokens = tokenize(lines, token='char')      #tokens是一个二维列表
for i in range(11)
自然语言处理(NLP)之一:文本预处理(文本准备) 拿到文本数据后,自然语言处理任务的第一步工作是文本(数据)准备或叫文本(数据)预处理。 文本预处理的流程如下图所示: 阅读详情

相关推荐

python 文本处理---英文文本预处理(简单易懂 全有注释)!!!!!使用正则表达式以及nltk库分词器双方法!

英文文本预处理---! 最近正在复习正则表达式,学习文本处理,今天就来处理一下英文文本,由于在下学到的知识不多,于是乎,只能写出下面的 一 些功能,虽然不是基于爬取网页后在进行网页分析,是直接对一个事先准备好的文本进行预处理,我的代码的功能有去除一个文本里面的所有中文文本,然后对英文单词进行分词处理。下面就来介绍一下吧! ...

weixin_45760635的博客 6128

python :中英文文本预处理(包含去标点分词词干提取)

python :中英文文本预处理(包含去标点/分词/词干提取) &amp;amp;nbsp; &amp;amp;nbsp; &amp;amp;nbsp; &amp;amp;nbsp;在做文本分析之前,一般我们都需要进行文本的预处理。这一步其实和做数据时的数据清洗非常的相像。在对文本进行清洗的时候,我们需要分成中文和英文两种语言来进行,因为语言的不同,我们需要进行的操作也不同: 英文:大小写的处理,标点符号的处理,文本的分词,去除停用词,以及词干的提取(cle...

海军上将光之翼的博客 2万+

python英文文本分析和提取_英文文本挖掘预处理流程总结

在中文文本挖掘预处理流程总结中,我们总结了中文文本挖掘的预处理流程,这里我们再对英文文本挖掘的预处理流程做一个总结。1. 英文文本挖掘预处理特点英文文本的预处理方法和中文的有部分区别。首先,英文文本挖掘预处理一般可以不做分词(特殊需求除外),而中文预处理分词是必不可少的一步。第二点,大部分英文文本都是uft-8的编码,这样在大多数时候处理的时候不用考虑编码转换的问题,而中文文本处理必须要处理un...

weixin_39717825的博客 2427

Python 英文文本预处理

目前在做2w+条web of science文献的文献计量分析,是科研训练的项目。老师说项目组都转python了,让我们自学python,所以完全处于小白状态的我一边摸索学python一边缓慢继续我的项目。 一开始是用python将7w+数据导入mysql数据库,筛选后还剩下2w+条,接下来是将每篇文献的摘要和标题进行预处理,构建语料库。 虽然还不清楚到底要构建什么类型的语料库,我个人理解还是...

weixin_37834134的博客 7904

python英文文本词频统计,python英文文章词频统计

通过这篇文章,我们学习了如何使用Python来统计英文文本和中文小说中的词频。通过使用正则表达式来处理文本,并使用字典来存储和计算词频,我们能够更好地理解文本中的词汇使用情况。这对于学术研究、语言分析和文本挖掘都非常有帮助。

a17348的博客 1738

使用Python实现文本英文统计功能

介绍了如何使用Python来实现文本英文统计,包括单词频率统计、词汇量统计以及文本情感分析等

inoing的博客 1995

4、I3C协议详解

I3C最初的设计目的是为移动设备创建一个能够使用多个传感器的单一接口。随着现代化移动设备对于传感器数量的增加以及对性能的提高,I2C和SPI已经达到了他们所能支持的临界点,而I3C的出现就是为了解决这一问题,I3C可以在同一根主线上支持更多的传感器设备,而且不会因为要支持中断或睡眠模式而增加额外的逻辑信号。I3C可以在更低功耗的情况下提供更快的传输速率,该特性的提升不止是对移动设备,对其他的嵌入式设备也都是很大的帮助。例如穿戴设备,需要在有限的物理空间中使用多个传感器并且要求更小的耗电。 一、简述..

迟子涵925的博客 2万+

麒麟桌面操作系统QT开发环境搭建

麒麟操作系统安装Qt

因为热爱,所以坚持,记录工作中的乐趣 9288

半导体领域知识 - 初级入门

半导体领域知识 - 初级入门 知识问答 1. 一个晶圆上根据芯片的大小,可以生产几百、几千、几万个芯片。如下图: 2. 8寸晶圆指的是什么?5nm工艺指的是什么? 8寸晶圆指的是直径为175mm(17.5cm)的晶圆,下面是6/812/18寸晶圆的尺寸以及相关发展历程。目前拥有12寸线的厂商只有5家,一个12寸晶圆厂的成本需要上百亿美金。 5nm工艺指的是在一个具体的芯片上,有很多微型结构(千万、亿级别的晶体管),这些核心基本单元MOS管的栅极宽度尺寸来衡量工艺的精细程度,如果是5nm就被称为5nm工艺

Hello World! 2万+

SAP资产按每天折旧功能介绍

注意:此处在计算百分比时将30天作为剩余使用寿命,因为SAPS/4HANA中的计算是通过考虑购置第一年的折旧总天数来进行的。这是因为我在计算总使用寿命时只使用了365天,如果剩余使用寿命大于1年,SAPS/4HANA会将闰年规范化为365天。此功能仅对确定使用寿命或剩余寿命百分比的折旧键有用,如果需要,这种折旧到日的解决方案可以应用于需要每天计算折旧的跨行业(任何国家/行业)。注意:这里在计算百分比时考虑了2天,因为364天已经过期,但目前我们到达2024年,使用寿命为366天。它只会在下一年生效。

yanzibing99的博客 1574

长短期记忆网络(LSTM)预测模型及其Python和MATLAB实现

LSTM 通过独特的门控机制解决了传统 RNN 的梯度消失和梯度爆炸问题,使其在处理长序列时具有显著优势。随着技术的不断发展,LSTM 及其变种(如 Bi-directional LSTM、Stacked LSTM 等)有望在更复杂的任务中发挥重要作用。2. **可视化真实值和预测值**:通过绘图来比较真实值和预测值,判断模型的准确性。2. **输入门(Input gate)**:决定当前的输入信息对细胞状态的影响。1. **细胞状态(Cell state)**:保持信息在时间步之间的传递。

qq_45441438的博客 2066

revit二次开发环境搭建(2024版)(小白友好)

revit二次开发环境配置,SDK、addin manager和lookup新手友好安装教程

m0_56961251的博客 1426

索尼IMX316 标定_ToF模块相机校准

很多东西一开始给出去的并不是最优的方案,而是在客户端支持中,以及在持续不断的芯片验证中,发现还可以这么做,还能够再提升Sensor的性能,所以说这是一个持续的过程。曾经听说过一个故事,在某厂里ST产品一直作为第一供应商多年,然后近段时间即将被新兴公司的ToF产品所打败,性能报告已经出来,但是ST并没有更新产品,而是在原有产品更新了固件以及标定流程,此时产品的性能又是超越其他供应商的产品。相机矩阵不考虑镜头失真,因为理想的针孔相机没有镜头。为了准确地代表一个真实的相机,相机模型包括径向和切向的镜头畸变。

dream it possible 1165

Modbus协议学习第四篇之线圈的概念

第一次在Modbus接触线圈的概念,应该是在介绍功能码的时候,因为其中有一个功能码是“读线圈状态”。我们可以把“线圈状态”理解为一种寄存器,类似于计算机中的寄存器概念,所以读线圈状态就是读某个寄存器,而这个特殊的寄存器其实就是一个bit,也就是要么是on/1,要么是off/0。把线圈状态理解成只能存一个bit信息的寄存器,就会很好理解线圈这个概念了。(免责声明:本博文仅供参考,因为博主也是初学者)

hzf978742221的博客 4643

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

上一篇: NLP_jieba中文分词的常用模块
下一篇: 语言模型n-grams:n元(语)法——python代码实现
Hiweir ·
博客等级 码龄3年 554粉丝 57原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值