it-idf with TfidfVectorizer 在日语文本上
it-idf with TfidfVectorizer on Japanese text
我正在处理大量用多种语言编写的文档。我想根据文档的 tf-idf 分数计算文档之间的余弦距离。到目前为止我有:
from sklearn.feature_extraction.text import TfidfVectorizer
# The documents are located in the same folder as the script
text_files = [r'doc1', r'doc2', r'doc3']
files = [open(f) for f in text_files]
documents = [f.read() for f in files]
vectorizer = TfidfVectorizer(ngram_range=(1,1))
tfidf = vectorizer.fit_transform(documents)
vocabulary = vectorizer.vocabulary_
当 doc1
、doc2
和 doc3
这三个文档包含英文文本时,该算法就像一个魅力,vocabulary
确实包含来自不同主体的 unigrams文本。我也试过用俄语,效果也很好。但是,当我尝试使用一些日文文本时,该算法不再按预期工作。
这个问题是因为日语没有空格,所以TfidfVectorizer 不明白什么是单词什么不是。例如,我的 unigram 词汇表中会有这样的内容:
診多索いほ権込真べふり告車クノ般宮えぼぜゆ注携ゆクく供9時ク転組けが意見だっあ税新ト復生ひり教台話辞ゃに
这显然是一个句子而不是一个词。我该如何解决这个问题?
你应该为日语提供分词器
vectorizer = TfidfVectorizer(ngram_range=(1,1), tokenizer=jap_tokenizer)
其中 jap_tokenizer
是您创建的函数或类似 this 的函数。
这似乎是 documents
的英文版本,基本上是:
documents = ['one word after another', 'two million more words', 'finally almost there']
对于你的日文文档,称它们为j_doc1
、j_doc2
和j_doc3
,documents
可能看起来像这样(只是一个例子;请耐心等待我没有费心去创造随机的日语句子):
documents = ['診多索いほ', '診多索いほ', '台話辞ゃに']
当前分词器查找 spaces,而您的字符串没有。你可以试试这个:
documents = [" ".join(char for char in d) for d in documents]
现在的文档是这样的,可能更可行(虽然这取决于你,因为我不知道在每个日文字符之间总是添加一个space是否合适):
documents
Out[40]: ['診 多 索 い ほ', '診 多 索 い ほ', '台 話 辞 ゃ に']
或定义您自己的分词器,如另一个答案中所述。
我正在处理大量用多种语言编写的文档。我想根据文档的 tf-idf 分数计算文档之间的余弦距离。到目前为止我有:
from sklearn.feature_extraction.text import TfidfVectorizer
# The documents are located in the same folder as the script
text_files = [r'doc1', r'doc2', r'doc3']
files = [open(f) for f in text_files]
documents = [f.read() for f in files]
vectorizer = TfidfVectorizer(ngram_range=(1,1))
tfidf = vectorizer.fit_transform(documents)
vocabulary = vectorizer.vocabulary_
当 doc1
、doc2
和 doc3
这三个文档包含英文文本时,该算法就像一个魅力,vocabulary
确实包含来自不同主体的 unigrams文本。我也试过用俄语,效果也很好。但是,当我尝试使用一些日文文本时,该算法不再按预期工作。
这个问题是因为日语没有空格,所以TfidfVectorizer 不明白什么是单词什么不是。例如,我的 unigram 词汇表中会有这样的内容:
診多索いほ権込真べふり告車クノ般宮えぼぜゆ注携ゆクく供9時ク転組けが意見だっあ税新ト復生ひり教台話辞ゃに
这显然是一个句子而不是一个词。我该如何解决这个问题?
你应该为日语提供分词器
vectorizer = TfidfVectorizer(ngram_range=(1,1), tokenizer=jap_tokenizer)
其中 jap_tokenizer
是您创建的函数或类似 this 的函数。
这似乎是 documents
的英文版本,基本上是:
documents = ['one word after another', 'two million more words', 'finally almost there']
对于你的日文文档,称它们为j_doc1
、j_doc2
和j_doc3
,documents
可能看起来像这样(只是一个例子;请耐心等待我没有费心去创造随机的日语句子):
documents = ['診多索いほ', '診多索いほ', '台話辞ゃに']
当前分词器查找 spaces,而您的字符串没有。你可以试试这个:
documents = [" ".join(char for char in d) for d in documents]
现在的文档是这样的,可能更可行(虽然这取决于你,因为我不知道在每个日文字符之间总是添加一个space是否合适):
documents
Out[40]: ['診 多 索 い ほ', '診 多 索 い ほ', '台 話 辞 ゃ に']
或定义您自己的分词器,如另一个答案中所述。