我有一个包含文本元素的列表。你知道吗
text = ['a for=apple','b for=ball', 'd for=dog', 'e for=elephant', 'a for=apple', 'd for=dog', '1.=one', '2.=two']
我需要在“=”之前获得文本的计数。我使用了CountVectorizer作为一个令牌模式,但它没有给出预期的结果
print(text)
vectorizer = CountVectorizer()
vectorizer = CountVectorizer(token_pattern="^[^=]+")
vectorizer.fit(text)
print(vectorizer.vocabulary_)
其输出如下
{'a for': 2, 'b for': 3, 'd for': 4, 'e for': 5, '1.': 0, '2.': 1}
但预期产出应该是
{'a for': 2, 'b for': 1, 'd for': 2, 'e for': 1, '1.': 1, '2.': 1}
我还需要从“1”中删除“.”,这样我的输出就可以
{'a for': 2, 'b for': 1, 'd for': 2, 'e for': 1, '1': 1, '2': 1}
我有办法做到吗?你知道吗
请注意,这只适用于
text
列表中所说的内容,即只包含一个=
,除此之外,还需要对其进行一些调整。你知道吗一个简单的方法是使用^{} :
它首先将文本中的每个字符串按
"="
分割成一个列表,并从中获取第一个元素。然后调用replace()
,用""
替换"."
的任何实例。最后,它返回counts的Counter()
对象。你知道吗注意:如果要在末尾返回纯字典,可以将
dict()
换行到最后一行。你知道吗相关问题 更多 >
编程相关推荐