tfidf sickitlearn将“word”与word分开

2024-10-05 14:27:47 发布

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

我正在处理文本分类中的一个问题,如果一个单词是以这种格式找到的,那么它的重要性将不同于以这种格式找到的

    import re
    from sklearn.feature_extraction.text import CountVectorizer
    sent1 = "The cat sat on my \"face\" face"
    sent2 = "The dog sat on my bed"
    content = [sent1,sent2]
    vectorizer = CountVectorizer(token_pattern=r"(?u)\b\w\w+\b|!|\?|\"|\'")
    vectorizer.fit(content)
    print (vectorizer.get_feature_names()) 

结果是

    ['"', 'bed', 'cat', 'dog', 'face', 'my', 'on', 'sat', 'the']

在我希望的地方

    ['bed', 'cat', 'dog', 'face','"face"' 'my', 'on', 'sat', 'the']

Tags: theimportonmy格式satfeaturecat
2条回答

你的令牌模式是

token_pattern=r"(?u)\b\w\w+\b|!|\?|\"|\'"

它正在查找单词(\b\w\w+\b)或感叹号、问号或引号。试试这样的

token_pattern=r"(?u)\b\w\w+\b|\"\b\w\w+\b\"|!|\?|\'"

注意这部分

\"\b\w\w+\b\"

寻找一个被引号括起来的词。你知道吗

您需要根据需要调整token_pattern参数。以下内容适用于所提供的示例:

pattern = r"\S+[^!?.\s]"
vectorizer = CountVectorizer(token_pattern=pattern)

但是,您可能需要进一步完善该模式。https://regex101.com可能有助于正确地使用正则表达式。你知道吗

相关问题 更多 >