这是我在StackOverflow上的第一篇文章,所以请原谅我可能犯的任何错误。我也是Python的新手,所以欢迎任何提示。我的问题很简单,但不管我试过什么,我似乎都想不通。这是我的代码:
import os
from bs4 import BeautifulSoup
import string
import nltk
from nltk import WordNetLemmatizer
from nltk.corpus import stopwords
from nltk import FreqDist
# For TF-IDF calculations
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.words)
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)
rootDir ='D:\rootDir'
testPath = r'D:\testPath'
trainPath = r'D:\trainPath'
data = []
lemmatizer = WordNetLemmatizer()
stop = stopwords.words("english")
stop += ['also']
bloblist_train = [tb('')] #Before EDIT: bloblist_train = tb('')
bloblist_test = [tb('')] #Before EDIT: bloblist_test = tb('')
for currentDirPath, subDirs, files in os.walk(rootDir):
for file in files:
with open(os.path.join(currentDirPath, file)) as dataFile:
inFile = dataFile.read()
html = BeautifulSoup(inFile, "html.parser")
text = html.get_text()
text_no_punc = text.translate(str.maketrans("", "", string.punctuation))
if testPath in currentDirPath:
bloblist_test += (tb(text_no_punc))
elif trainPath in currentDirPath:
bloblist_train += tb(text_no_punc)
words = text_no_punc.split()
data = data + words
我正在遍历一个包含HTML文档的更大的文件目录,并对它们进行解析,然后进一步尝试为每个单词找到TF-IDF。我使用了包和类的混合,包括beauthoulsoup、NLTK和TextBlob。我使用TextBlob来查找TF-IDF,但是遇到了创建TextBlob列表的问题。我遇到的具体问题是:
^{pr2}$代码目前只创建一个巨大的TextBlob,所有文档都连接为一个TextBlob。我想每个文件都有一个TextBlob。我也尝试过以下方法
if testPath in currentDirPath:
bloblist_test.append(tb(text_no_punc))
elif trainPath in currentDirPath:
bloblist_train.append(tb(text_no_punc))
从而得出错误:
AttributeError: 'TextBlob' object has no attribute 'append'
我错过了什么?Append是我用来创建列表python字符串的方法,如下所示:
s1 = [1,2,3]
s2 = [4,5]
s1.append(s2)
# Output: [[1,2,3], [4,5]]
但是TextBlobs显然不支持这一点。在
那么我该如何创建这些textblob的列表呢?在
编辑:
因此,我自己取得了一些进展,但仍然无法格式化列表。我没有将bloblist_train
和bloblist_test
初始化为tb('')
,而是将它们设置为[tb('')]
,因为正如我的问题所说,它们应该包含一个textblob的列表,而不仅仅是textblob。所以现在看来…它起作用了!有一件事我似乎还是搞不好:它现在的方式创建了一个列表,其中第一项是一个空的TextBlob(例如[TextBlob(""), TextBlob("one two three")]
)。在
我意识到这是一个与我刚开始的问题稍有不同的问题,所以如果有人认为我需要结束这个问题并开始另一个问题,请告诉我。我又是新来的。
如果没有,我觉得有一个简单的关键字或语法解决方案,我会非常感谢你的一些意见。在
我最终自己找到了答案。我知道答案似乎微不足道,但事实上它与Textblob一起工作,我认为它会改变答案的本质。好吧,没有。我对那些经验丰富的Python们不假思索地通过我的问题感到失望,因为我所要做的就是:
我在其他语言的领域中被混淆了,比如C++,我必须把变量初始化成它们的预期类型。相反,多亏了出色的python,我只需要声明一个列表,然后向其中添加一些内容。对于像我这样的初学者,请记住,python不关心列表中有什么。它可以是你放在那里的任何对象的混合体:int、char、string、Textblob等等,只要告诉它你有一个列表,然后添加。相关问题 更多 >
编程相关推荐