【文本预处理】

  文本预处理的核心思想是如何将文本中转化成能够训练的样本,而且通常情况下是转化成序列数据。通常有以下几个步骤:

通常英文和中文的处理会有些差别,我们分别举例讲解

处理英文文本

  • 加载原始文本(一般我们按行来进行处理,因此一行一行的读)
import collections
import re
from d2l import torch as d2l
# 这里主要是懒得再去下载英文文章了,就直接copy的李沐老师的代码
d2l.DATA_HUB['time_machine'] = (d2l.DATA_URL + 'timemachine.txt',
                                '090b5e7e70c295757f55df93cb0a180b9691891a')

def read_time_machine():  
    """将时间机器数据集加载到文本行的列表中"""
    with open(d2l.download('time_machine'), 'r') as f:
        lines = f.readlines()
    return [re.sub('[^A-Za-z]+', ' ', line).strip().lower() for line in lines]
    # 这一步是暴力将所有非英文字符全部替换并转换成小写
    # 可能会有一些问题,但是无伤大雅

lines = read_time_machine()
print(lines[0])
print(lines[10])
the time machine by h g wells
twinkled and his usually pale face was flushed and animated the
  • 获得每一行句子的token(可以理解为词汇表)
# 这里由于是英文,都是空格分割,相对好处理,中英文的处理差别就在这儿
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('错误:未知词元类型:' + token)

tokens = tokenize(lines)
for i in range(11):
    print(tokens[i])
['the', 'time', 'machine', 'by', 'h', 'g', 'wells']
[]
[]
[]
[]
['i']
[]
[]
['the', 'time', 'traveller', 'for', 'so', 'it', 'will', 'be', 'convenient', 'to', 'speak', 'of', 'him']
['was', 'expounding', 'a', 'recondite', 'matt
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜鸟炼丹师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值