用Python读红楼
最近受到这篇文章用Python读金庸武侠的启发。作为古典文(zhuang)学(bi)青年,一定要用Python来试试我读了20年的《红楼梦》。
首先从网上找到了红楼梦.txt(不清楚版本,可能是程甲版)和对应的人物表。
把人名加入词库,然后用结巴分词切分整个文章(我没有区分前八十回和后四十回),加入gensim的训练中
def tranning():
with open('hlm.txt') as f:
data = [line.strip()
for line in f.readlines()
if line.strip()]
sentences = []
for line in data:
words = list(jieba.cut(line))
sentences.append(words)
model = gensim.models.Word2Vec(sentences,
size=100,
window=5,
min_count=5,
workers=4)
return model
训练生成一个以词向量表示词的模型,下面就用代码来找找和宝钗相似的人物吧。
for k, s in model.most_similar(positive=["宝钗"]):
print('{}:{}'.format(k, s))
探春:0.9595787525177002
紫鹃:0.9429049491882324
黛玉:0.9325058460235596