【发布时间】:2016-03-16 01:26:54
【问题描述】:
我正在尝试调整此代码(找到源代码here)以遍历文件目录,而不是对输入进行硬编码。
#!/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
类似的问题here 并没有完全解决问题。我想知道如何调用文件来计算idf,但单独维护它们以计算完整的tf-idf?
【问题讨论】: