我正在尝试调整此代码(在此处找到源代码)以遍历文件目录,而不是对输入进行硬编码。
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import division, unicode_literals
import math
from textblob import TextBlob as tb
def tf(word, blob):
return blob.words.count(word) / len(blob.words)
def n_containing(word, bloblist):
return sum(1 for blob in bloblist if word in blob)
def idf(word, bloblist):
return math.log(len(bloblist) / (1 + n_containing(word, bloblist)))
def tfidf(word, blob, bloblist):
return tf(word, blob) * idf(word, bloblist)
document1 = tb("""Today, the weather is 30 degrees in Celcius. It is really hot""")
document2 = tb("""I can't believe the traffic headed to the beach. It is really a circus out there.'""")
document3 = tb("""There are so many tolls on this road. I recommend taking the interstate.""")
bloblist = [document1, document2, document3]
for i, blob in enumerate(bloblist):
print("Document {}".format(i + 1))
scores = {word: tfidf(word, blob, bloblist) for word in blob.words}
sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True)
for word, score in sorted_words:
score_weight = score * 100
print("\t{}, {}".format(word, round(score_weight, 5)))
我想在目录中使用一个输入 txt 文件,而不是每个硬编码的document
.
例如,假设我有一个目录foo
,其中包含三个文件file1
, file2
, file3
.
文件1包含包含的内容document1
,即
文件1:
Today, the weather is 30 degrees in Celcius. It is really hot
文件2包含包含的内容document2
,即
I can't believe the traffic headed to the beach. It is really a circus out there.
文件3包含包含的内容document3
,即
There are so many tolls on this road. I recommend taking the interstate.
我不得不使用它glob
来实现我想要的结果,并且我提出了以下代码适配,它可以正确识别文件,但不会像原始代码那样单独处理它们:
file_names = glob.glob("/path/to/foo/*")
files = map(open,file_names)
documents = [file.read() for file in files]
[file.close() for file in files]
bloblist = [documents]
for i, blob in enumerate(bloblist):
print("Document {}".format(i + 1))
scores = {word: tfidf(word, blob, bloblist) for word in blob.words}
sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True)
for word, score in sorted_words:
score_weight = score * 100
print("\t{}, {}".format(word, round(score_weight, 5)))
如何使用 维护每个单独文件的分数glob
?
使用目录中的文件作为输入后的预期结果将与原始代码相同[结果被截断到前 3 位以获得空间]:
Document 1
Celcius, 3.37888
30, 3.37888
hot, 3.37888
Document 2
there, 2.38509
out, 2.38509
headed, 2.38509
Document 3
on, 3.11896
this, 3.11896
many, 3.11896
这里有一个类似的问题并没有完全解决问题。我想知道如何调用文件来计算idf
但单独维护它们以计算完整tf-idf
?