搜索文本
-
指定单词每次出现,连同上下文一起显示,用函数concordance: 比如来查一下《白鲸记》中的词monstrous:
text1.concordance("monstrous")
-
搜索与某个单词出现类似上下文中的单词
text1.similar("monstrous")
-
具有共同上下文的多个单词
text2.common_contexts(["monstrous", "very"]) -> be_glad am_glad a_pretty is_pretty a_lucky
-
单词在文本中的离散图
text4.dispersion_plot(["citizens", "democracy", "freedom", "duties", "America"])
计数词汇
-
获取词汇排序表(按照单词顺序排列)
sorted(set(text3)) #set去重,sorted排序
-
文本词汇丰富度,每个字平均被使用次数
from __future__ import division -> len(text3) / len(set(text3))
-
计数一个词在文本中出现的次数,计算一个特定的词在文本中占据的百分比。
text3.count("smote") 100 * text4.count('a') / len(text4)
频率分布
-
统计文本中词频FreqDist
fdist1 = FreqDist(text1)
-
查看文本只出现一次的词
fdist1.hapaxes()
-
所有长度超过7 个字符出现次数超过7 次的词:
fdist5 = FreqDist(text5) sorted([w for w in set(text5) if len(w) > 7 and fdist5[w] > 7])
词语搭配和双连词(bigrams)
-
双连词,bigrams生成的是generator,查看需要用list()函数转换为数组
bigrams(['more', 'is', 'said', 'than', 'done']) ->[('more', 'is'), ('is', 'said'), ('said', 'than'), ('than', 'done')]
-
找到文本中频繁的双连词,用collocations()函数
text4.collocations() ->United States; fellow citizens; years ago; Federal Government;......
频率分类定义函数
fdist = FreqDist(samples) | 创建包含给定样本的频率分布 |
---|---|
fdist.inc(sample) | 增加样本 |
fdist[‘monstrous’] | 计数给定样本出现的次数 |
fdist.freq(‘monstrous’) | 给定样本的频率 |
fdist.N() | 样本总数 |
fdist.keys() | 以频率递减顺序排序的样本链表 |
for sample in fdist: | 以频率递减的顺序遍历样本 |
fdist.max() | 数值最大的样本 |
fdist.tabulate() | 绘制频率分布表 |
fdist.plot() | 绘制频率分布图 |
fdist.plot(cumulative=True) | 绘制累积频率分布图 |
fdist1 < fdist2 | 测试样本在fdist1 中出现的频率是否小于fdist2 |
python数组表达式
[w for w in text if condition]
其中condition为满足的测试条件。一些测试属性的表达函数为:
函数 | 含义 |
---|---|
s.startswith(t) | 测试s 是否以t 开头 |
s.endswith(t) | 测试s 是否以t 结尾 |
t in s | 测试s 是否包含t |
s.islower() | 测试s 中所有字符是否都是小写字母 |
s.isupper() | 测试s 中所有字符是否都是大写字母 |
s.isalpha() | 测试s 中所有字符是否都是字母 |
s.isalnum() | 测试s 中所有字符是否都是字母或数字 |
s.isdigit() | 测试s 中所有字符是否都是数字 |
s.istitle() | 测试s 是否首字母大写(s 中所有的词都首字母大写) |
对每个元素进行操作
表达式为
[f(w) for ...]或[w.f() for ...]
比如
[w.upper() for w in text1]