【问题标题】:How to force sklearn CountVectorizer to not remove special characters (i.e. #, @, , $ or %)如何强制 sklearn CountVectorizer 不删除特殊字符(即 #、@、、$ 或 %)
【发布时间】:2019-12-16 20:22:21
【问题描述】:

这是我的代码:

count = CountVectorizer(lowercase = False)

vocabulary = count.fit_transform([words])
print(count.get_feature_names())

例如,如果:

 words = "Hello @friend, this is a good day. #good."

我想把它分成这个:

['Hello', '@friend', 'this', 'is', 'a', 'good', 'day', '#good']

目前,它是这样分成的:

['Hello', 'friend', 'this', 'is', 'a', 'good', 'day']

【问题讨论】:

    标签: python machine-learning scikit-learn


    【解决方案1】:

    您可以在CountVectorizer 中使用token_pattern 参数,如documentation 中所述:

    传递一个正则表达式来告诉 CountVectorizer 什么应该被视为一个词。假设在这种情况下,我们告诉 CountVectorizer,即使带有 # 或 @ 的单词也应该是一个单词。然后做:

    count = CountVectorizer(lowercase = False, token_pattern = '[a-zA-Z0-9$&+,:;=?@#|<>.^*()%!-]+')
    

    输出:

    ['#good', '@friend', 'Hello', 'a', 'day', 'good', 'is', 'this']
    

    【讨论】:

    • 另外,我将如何强制 CountVectorizer 忽略某些单词?如果单词是:words = “Hello @friend, this is a good day https://www.google.com/. #good." 我希望它仍然被分成:['Hello', 'friend', 'this', 'is', 'a', 'good', 'day'] 没有 URL。非常感谢!
    • 您可以传递另一个名为 stop_words 的参数并指定要忽略的单词列表。请检查我发布的文档链接,它写在那里:)
    • 有什么方法可以设置参数,以便删除任何包含https 的字符串,以删除出现的任何 URL。?再次非常感谢。
    • 您可以首先通过删除所有 https 链接来清理您的字符串:words = re.sub(r"\bhttps:\//[a-z0-9.]*", '', words),然后继续使用通常的解决方案。 :)
    猜你喜欢
    • 1970-01-01
    • 2014-05-04
    • 2010-10-14
    • 2022-08-03
    • 1970-01-01
    • 2019-06-09
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    相关资源
    最近更新 更多