1 文本加载

文本处理函数学习

re.sub():正则表达式替换函数,对于输入的一个字符串,利用正则表达式(的强大的字符串处理功能),去实现(相对复杂的)字符串替换处理,然后返回被替换后的字符串,实现比普通字符串的replace更加强大的替换功能。

import re
s= "大家好,我是一个小白。I 'm so glad to introduce myself, and I’m 18 years old.   Today is 2020/01/01. It is a wonderful DAY!"
re.sub(r'[a-z]', '*', s) # 匹配单一小写字母,并替换为*
re.sub(r'[A-Z]', '*', s)  # 表示只匹配单一大写字母,并替换为*
re.sub(r'[A-Za-z]', '*', s) # 表示只匹配单一字母,并替换为*
re.sub(r'[0-9]+', '*', s) # 表示匹配多个连续的数字,并替换为*
re.sub(r'[A-Za-z]+', '*', s) # 表示匹配多个连续的字母,并替换为*
re.sub(r'[^a-z]', '*', s) # 表示匹配单个非小写字母

strip():想去掉字符串里面的哪些字符,那么你就把这些字符当参数传入。此函数只会删除头和尾的字符,中间的不会删除。)

如果strip()的参数为空,那么会默认删除字符串头和尾的空白字符(包括\n,\r,\t这些

词元化

将列表化的句子一个一个拆成word或者str,形成token(词元)

2 构建语料库(corpus)

#mermaid-svg-i69DtK9sDl4V9S6v {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-i69DtK9sDl4V9S6v .error-icon{fill:#552222;}#mermaid-svg-i69DtK9sDl4V9S6v .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-i69DtK9sDl4V9S6v .edge-thickness-normal{stroke-width:2px;}#mermaid-svg-i69DtK9sDl4V9S6v .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-i69DtK9sDl4V9S6v .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-i69DtK9sDl4V9S6v .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-i69DtK9sDl4V9S6v .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-i69DtK9sDl4V9S6v .marker{fill:#333333;stroke:#333333;}#mermaid-svg-i69DtK9sDl4V9S6v .marker.cross{stroke:#333333;}#mermaid-svg-i69DtK9sDl4V9S6v svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-i69DtK9sDl4V9S6v .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-i69DtK9sDl4V9S6v .cluster-label text{fill:#333;}#mermaid-svg-i69DtK9sDl4V9S6v .cluster-label span{color:#333;}#mermaid-svg-i69DtK9sDl4V9S6v .label text,#mermaid-svg-i69DtK9sDl4V9S6v span{fill:#333;color:#333;}#mermaid-svg-i69DtK9sDl4V9S6v .node rect,#mermaid-svg-i69DtK9sDl4V9S6v .node circle,#mermaid-svg-i69DtK9sDl4V9S6v .node ellipse,#mermaid-svg-i69DtK9sDl4V9S6v .node polygon,#mermaid-svg-i69DtK9sDl4V9S6v .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-i69DtK9sDl4V9S6v .node .label{text-align:center;}#mermaid-svg-i69DtK9sDl4V9S6v .node.clickable{cursor:pointer;}#mermaid-svg-i69DtK9sDl4V9S6v .arrowheadPath{fill:#333333;}#mermaid-svg-i69DtK9sDl4V9S6v .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-i69DtK9sDl4V9S6v .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-i69DtK9sDl4V9S6v .edgeLabel{background-color:#e8e8e8;text-align:center;}#mermaid-svg-i69DtK9sDl4V9S6v .edgeLabel rect{opacity:0.5;background-color:#e8e8e8;fill:#e8e8e8;}#mermaid-svg-i69DtK9sDl4V9S6v .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-i69DtK9sDl4V9S6v .cluster text{fill:#333;}#mermaid-svg-i69DtK9sDl4V9S6v .cluster span{color:#333;}#mermaid-svg-i69DtK9sDl4V9S6v div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-i69DtK9sDl4V9S6v :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;}

Yes
No
词元化
构建语料库
统计token的频率
大于阈值词频?
读取文本数据集
循环添加序号
结束
构建getitem

2.3 示例代码

import d2I.torch1 as d2l
import torch
import collections
import re# 载入文本数据,并通过正则化去点除字母外的文字,并且转化为小写
def load_machine_time():with open(r'../data/txt/timemachine.txt') as f:lines = f.readlines()new = [re.sub(r'[^A-Za-z]+',' ',line).strip().lower() for line in lines]return new# 将得到的data,根据词元的要求转化为词元
def tokenize(lines,token='word'):if token == 'word':return [line.split() for line in lines]elif token == 'char':return [list(line) for line in lines]else:print('Error'+token)# 构建语料库corpus:
class corpus:def __init__(self,min_freqs=0,token=None,reversed_token=None):self.min_freqs = min_freqsif token is None:token = []if reversed_token is None:reversed_token = []freqs = count_freqs(token)self.token_freq = sorted(freqs.items(),key=lambda x:x[1],reverse=True)self.idx_to_token = ['<unk>']+reversed_tokenself.token_to_idx = {token:idx for idx,token in enumerate(self.idx_to_token)}for token,freq in self.token_freq:if freq < self.min_freqs:breakif token not in self.idx_to_token:self.idx_to_token.append(token)self.token_to_idx[token] = len(self.idx_to_token) - 1def __getitem__(self, tokens):if not isinstance(tokens,(list,tuple)):return self.token_to_idx.get(tokens,self.unk)return [self.__getitem__(token) for token in tokens]def __len__(self):return len(self.idx_to_token)def to_token(self,indices):if not isinstance(indices,(list,tuple)):return self.idx_to_token[indices]return [self.idx_to_token[indice] for indice in indices]@propertydef get_freq(self):return self.token_freq@propertydef unk(self):return 0# 统计词语出现的频率
def count_freqs(tokens):new = Noneif len(tokens)==0 or isinstance(tokens,list):new = [token for line in tokens for token in line]freqs =  collections.Counter(new)return freqsdef create_time_machine_corpus(max_slices=-1):data = load_machine_time()tokens = tokenize(data, token='char')vocab = corpus(token=tokens)'''这里的vocab[]:就是调用的vocab里面的__getitem__方法'''corpuss = [vocab[token] for list in tokens for token in list]if max_slices > 0:corpuss = corpuss[:max_slices]return vocab,corpussif __name__ == '__main__':data = load_machine_time()print('文本长度:',len(data))for i in range(10):print(data[i])tokens = tokenize(data,token='word')for i in range(10):print(tokens[i])vocab = corpus(token=tokens)print(list(vocab.token_to_idx.items())[:10])for i in range(10):print('文本:',tokens[i])print('索引:',vocab[tokens[i]])vocab,corpuss = create_time_machine_corpus(max_slices=-1)print(len(vocab),len(corpuss))

NLP语料库构建(corpus)相关推荐

  1. NLP——语料库信息提取和处理方法

    NLP--语料库信息提取和处理方法 本文以搜狗新闻语料为例,记录文本语料的收集.读取.处理等一整套的方法,主要是为了排排坑. 文章目录 NLP--语料库信息提取和处理方法 前言 一.语料下载 二.文件 ...

  2. 计算机语言学 语料库,语料库语言学 (Corpus Linguistics).pdf.pdf

    语料库语言学 (Corpus Linguistics).pdf 语料库语言学 (CORPUS LINGUISTICS) 绪论绪论((IINTRODUCTIONNTRODUCTION)) 邹煜邹煜 zo ...

  3. 中文幽默语料库构建与计算项目(幽默等级识别,幽默类型识别,隐喻类型识别,隐喻情绪识别)

    ChineseHumorSentiment chinese Humor Detection or Computation based on corpus and nlp methods, 基于语料库与 ...

  4. 【收集】NLP语料库数据集+持续更新

    来源:大数据文摘 本文共4270字,建议阅读7分钟. 本文为你奉上100多个按字母顺序排列的开源自然语言处理文本数据集列表. 奉上100多个按字母顺序排列的开源自然语言处理文本数据集列表(原始未结构化 ...

  5. 日语配合计算机应用技术,基于计算机协同工作技术的日语语料库构建及应用

    [摘 要] 计算机协同工作是结合人与计算机网络.软件以及硬件等相关技术进行协同工作的方法.基于计算机系统工作的相关技术支持群体成员在共享资源和信息的环境下的协同工作.共同完成某项任务的应用系统.本文介 ...

  6. 70+个NLP语料库数据集

    TED演讲数据集 女性用户网购服装反馈数据集 新闻类别数据集 中华古诗数据集 中文敏感词库 人民日报文章数据集(1979-2010) 人民日报文章数据集(1949-1978) 1998人民日报标注语料 ...

  7. NLP之路-查看获取文本语料库

    继续学习NLP in Python #coding=UTF-8 #上面一句解决中文注释编码错误问题 import nltk #查看获取到的文本语料库 nltk.corpus.gutenberg.fil ...

  8. NLP(一)语料库和WordNet

    访问语料库 NLTK数据库的安装:http://www.nltk.org/data.html NLTK语料库列表:http://www.nltk.org/nltk_data/ 内部访问(以Reuter ...

  9. nlp自己制作一个语料库_第119天的nlp论文总结了一个论点注释的科学出版物的语料库...

    nlp自己制作一个语料库 内置AI NLP365(INSIDE AI NLP365) Project #NLP365 (+1) is where I document my NLP learning ...

最新文章

  1. Android Studio中RecycerView依赖库加载问题
  2. I210网卡LINUX的mac,linux i210 网卡驱动解读
  3. 压缩网络模型,或者是融合多个神经网络
  4. python主要用途-python的主要用途是什么
  5. python3.6.5安装-Ubuntu16.04安装python3.6.5详细步骤
  6. tplink-wr841n无线路由接入到局域网三层交换机方法
  7. FineUI(专业版)v3.0.0 发布,手机、平板和桌面全支持!
  8. c语言定义64位的变量,李洪强-C语言9-C语言的数据,变量和常量
  9. ngxin做http强制跳转https,接口的POST请求变成了GET
  10. C/C++ Bug记录
  11. 【Prison Break】第八天(4.4)
  12. php之thinkphp3.2.3 文件访问路径,URL路由配置-与重定向
  13. 微信小程序订阅消息 微信公众号模板消息
  14. Linux:文件系统和数据资料
  15. VLIW技术与嵌入式系统
  16. 浅谈车载控制器产线EOL实现方式
  17. MCAL配置-Cdd_Ipc
  18. 让IE窗口最小化最大化的快捷键
  19. Photoshop怎样快速调整画笔大小
  20. 数据库中LIMIT和 OFFSET的理解

热门文章

  1. 微服务架构下,解决数据库跨库查询的一些思路
  2. Android-x86 项目简介
  3. RS232转RS484接线图
  4. 图像处理:显著性区域检测总结(一)
  5. FreeCAD学习笔记——Units、Builtin modules和Workbench creation
  6. 广州大学计算机网络实验五,计算机网络实验五.doc
  7. xcode打包IPA上架App Store图文详解
  8. C-E question 整理
  9. Sqlserver 双机热备份_主数据库发布(主从备份)
  10. 基于matlab的自适应LMS算法实现