我正在处理文本分类中的一个问题,如果以这种格式"单词">找到一个单词,它将与在此格式中找到单词具有不同的重要性,所以我尝试了此代码
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)bww+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']
您的令牌模式是
token_pattern=r"(?u)bww+b|!|?|"|'"
查找单词 (\b\w\w+\b( 或感叹号,或问号或引号。尝试类似的东西
token_pattern=r"(?u)bww+b|"bww+b"|!|?|'"
注意部分
"bww+b"
它寻找一个用引号括起来的单词。
您需要根据需要调整token_pattern
参数。以下内容应该适用于提供的示例:
pattern = r"S+[^!?.s]"
vectorizer = CountVectorizer(token_pattern=pattern)
但是,您可能需要进一步优化模式。 https://regex101.com 可能有助于让您的正则表达式恰到好处。