全部JupyterNotebook来自
https://github.com/ShusenTang/Dive-into-DL-PyTorch
主要是做一些基础知识的记录
第二次的内容是文本预处理,语言模型,循环神经网络基础。
1.re
re 即正则表达式 regular expression。从这段代码上看,python 的写法确实优雅re.sub(a, b, c)是将c中所有a的子串替换成b。
这里使用了一个正则表达式[^a-z]+,代表所有长度大于1的非小写字母构成的子串。但是,先re.sub(), 然后再strip 会比较合理。非字母的字符经过转换后可能会在末尾留下空格。
import collections
import re
def read_time_machine():
with open('/home/kesci/input/timemachine7163/timemachine.txt', 'r') as f:
lines = [re.sub('[^a-z]+', ' ', line.strip().lower()) for line in f]
return lines
lines = read_time_machine()
print('# sentences %d' % len(lines))