从元素列表中提取文本计数

2024-04-26 21:32:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含文本元素的列表。你知道吗

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}

我有办法做到吗?你知道吗


Tags: text文本元素apple列表forone计数
3条回答
import re
dictionary = {}

def remove_special_characters(value):
    if '.' in value:
        return re.sub(r'\.=\w+','',value)
    return value.split('=')[0]
for value in text:
    new_value = remove_special_characters(value)
    if new_value in dictionary:
        dictionary[new_value] += 1
    else:
        dictionary[new_value] = 1
print(dictionary)
>>>{'a for': 2, 'b for': 1, 'd for': 2, 'e for': 1, '1': 1, '2': 1}
from collections import Counter

text = ['a for=apple','b for=ball', 'd for=dog', 'e for=elephant', 'a for=apple', 'd for=dog', '1.=one', '2.=two']

text = [i.split('=')[0] for i in text]      #consider only the first part of the split
text = [i.split('.')[0] for i in text]
frequency = {}
for each in text:
    if each in frequency:
        frequency[each] += 1
    else:
        frequency[each] = 1
print(frequency)                        #if you want to use dict

counts =list(Counter(text).items())     #if you want to use collections module
print(counts)

请注意,这只适用于text列表中所说的内容,即只包含一个=,除此之外,还需要对其进行一些调整。你知道吗

一个简单的方法是使用^{}

>>> from collections import Counter
>>> text = ['a for=apple','b for=ball', 'd for=dog', 'e for=elephant', 'a for=apple', 'd for=dog', '1.=one', '2.=two']
>>> Counter(x.split('=')[0].replace('.', '') for x in text)
Counter({'a for': 2, 'd for': 2, 'b for': 1, 'e for': 1, '1': 1, '2': 1})

它首先将文本中的每个字符串按"="分割成一个列表,并从中获取第一个元素。然后调用replace(),用""替换"."的任何实例。最后,它返回counts的Counter()对象。你知道吗

注意:如果要在末尾返回纯字典,可以将dict()换行到最后一行。你知道吗

相关问题 更多 >