<p>使用sklearn的<a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html" rel="nofollow noreferrer">CountVectorizer</a>:</p>
<pre><code>from sklearn.feature_extraction.text import CountVectorizer
df = pd.DataFrame({'texts': ["This is one text (the first one)",
"This is the second text",
"And, finally, a third text"
]})
cv = CountVectorizer()
cv.fit(df['texts'])
results = cv.transform(df['texts'])
print(results.shape) # Sparse matrix, (3, 9)
</code></pre>
<p>如果语料库足够小,可以放入您的内存(2000+足够小),您可以将稀疏矩阵转换为pandas数据帧,如下所示:</p>
^{pr2}$
<p><code>df_res</code>是您想要的结果:</p>
<pre><code>df_res
index and finally first is one second text the third this
0 0 0 1 1 2 0 1 1 0 1
1 0 0 0 1 0 1 1 1 0 1
2 1 1 0 0 0 0 1 0 1 0
</code></pre>
<hr/>
<p>如果您得到一个<code>MemoryError</code>,您可以减少单词的词汇表,以考虑使用<code>CountVectorizer</code>的不同参数:</p>
<ol>
<li>将参数<code>stop_words='english'</code>设置为忽略英文非字词(如<code>the</code>和`and)</li>
<li>使用<code>min_df</code>和{<cd7>},这使得<code>CountVectorizer</code>根据文档频率忽略一些单词(太频繁或很少出现的单词,这可能是无用的)</li>
<li>使用<code>max_features</code>,只使用最常见的<code>n</code>单词。在</li>
</ol>