import collections
import tensorflow as tf
def _read_words(filename):
with tf.gfile.GFile(filename, "r") as f:
return f.read().decode("utf-8").replace("\n", "<eos>").split()
def _build_vocab(filename):
data = _read_words(filename)
counter = collections.Counter(data)
count_pairs = sorted(counter.items(), key=lambda x: (-x[1], x[0]))
words, _ = list(zip(*count_pairs))
word_to_id = dict(zip(words, range(len(words))))
return word_to_id摘自
https://github.com/tensorflow/models/blob/master/tutorials/rnn/ptb/reader.py
经典的把一篇英文文章转成word2id形式的dict的一段python程序
构建词汇表与读取文本
最新推荐文章于 2024-02-16 18:08:54 发布
本文介绍了一种从文件中读取文本并构建词汇表的方法。通过使用TensorFlow和collections库,文中定义了两个函数:_read_words用于读取文件内容并将换行符替换为<eos>标记;_build_vocab用于构建词汇表,统计词频并按频率排序。
部署运行你感兴趣的模型镜像
您可能感兴趣的与本文相关的镜像
TensorFlow-v2.15
TensorFlow
TensorFlow 是由Google Brain 团队开发的开源机器学习框架,广泛应用于深度学习研究和生产环境。 它提供了一个灵活的平台,用于构建和训练各种机器学习模型
6729

被折叠的 条评论
为什么被折叠?



