快速答案
本答案页包含 Python 分词与文本向量 的 4 道选择题、4 道填空题和 4 道输出预测题,每题都给出准确答案和简短解释。
答案已完整展示,建议先尝试作答,再用本页核对。第一次练习最好从互动练习页开始。
分词做了什么?
答案: 把文本切成更小的单元
为什么: 分词把字符串变成后续步骤可以索引或嵌入的词元。
为什么要构造一个共享词表?
答案: 让每篇文档使用相同的向量维度
为什么: 共享词表让每个词元在所有文档中都有稳定位置。
词袋向量忽略了什么?
答案: 词序
为什么: 词袋保留计数,但丢弃词元出现的顺序。
运行结果是什么?
import re
def tokenize(text):
return re.findall(r"[a-z']+", text.lower())
print(tokenize("Python, text!"))答案: ['python', 'text']
为什么: 文本先转成小写,正则只保留字母,因此标点被去掉。
补全提取小写单词词元的正则表达式。
import re
text = "Python, text!"
print(re.findall(r"____", text.lower()))答案: [a-z']+
为什么: 字符类接受字母和撇号,加号表示一个或多个。
补全点积中用于配对的函数。
a = [1, 2]
b = [3, 4]
print(sum(x * y for x, y in ____(a, b)))答案: zip
为什么: zip 把两个向量中对应位置的元素配对。
补全零向量保护条件。
import math
def cosine(a, b):
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
if not norm_a or not ____:
return 0.0
return 1.0
print(cosine([0, 0], [1, 1]))答案: norm_b
为什么: 任一长度为 0 都会让分母为零,所以两个都要检查。
补全用于增加计数的词表查找。
index = {"python": 0, "text": 1}
counts = [0, 0]
counts[____["text"]] += 1
print(counts)答案: index
为什么: 索引把词元映射到向量中的位置。
这段程序打印出什么?
import re
def tokenize(text):
return re.findall(r"[a-z']+", text.lower())
print(tokenize("Python makes text small."))答案: ['python', 'makes', 'text', 'small']
为什么: 函数把句子转成小写,并提取四个单词词元。
代码的输出结果是什么?
def vector(text, index):
counts = [0] * len(index)
for word in text.split():
if word in index:
counts[index[word]] += 1
return counts
index = {"python": 0, "text": 1}
print(vector("python text text", index))答案: [1, 2]
为什么: 向量记录一个 python 词元和两个 text 词元。
屏幕上会显示什么?
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
return dot / (norm_a * norm_b)
print(round(cosine([1, 1], [2, 2]), 1))答案: 1.0
为什么: 两个向量方向相同,所以余弦相似度是 1.0。
这段代码会输出什么?
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
if not norm_a or not norm_b:
return 0.0
return dot / (norm_a * norm_b)
print(round(cosine([1, 0], [0, 1]), 1))答案: 0.0
为什么: 两个向量没有共享维度,所以点积为零。
先试一遍题目
打开 Python 分词与文本向量 练习页,用即时反馈回答同样的 12 道题。