我有一个很大的文本语料库,我想在其中运行一些算法。这些算法并不关心单词是什么——单词对它们来说只是一个独特的对象。因此,我想通过简单地用整数 ID 替换单词来减小文本的大小。
一个例子:
my_string = "an example sentence with an example repetition."
my_ids = get_ids_from_string(my_string)
print my_ids
>>> [0, 1, 2, 3, 0, 1, 4] ### note that the ID for 'example' is always the same
我正在寻找一种简洁、高效、Python 的方法来解决这个问题。
最佳答案
用整数替换字符串并不能带来多大好处——确保相同的字符串在内存中只存储一次也能带来同样多的好处。
my_string = "an example sentence with an example repetition."
words = my_string.split()
unique_words = [intern(word) for word in words]
“unique_words”列表等于“words”列表,但 intern()
保证字符串将被使用一次。如果您在包含少量可能单词的大型文本语料库上执行此操作,则它不会比整数使用更多的内存。
关于python - 为给定的单词集创建 id 的简单 [pythonic] 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20750051/