我正在为我的文档字典中的所有单词计算inverse_document_frequency,我必须根据查询得分显示排名前5的文档。但是我在创建包含文档中单词词汇表的语料库时陷入了循环。请帮助我改进我的代码。这段代码用于读取我的文件,删除标点符号和停止文件中的单词。
def wordList(doc):
"""
1: Remove Punctuation
2: Remove Stop Words
3: return List of Words
"""
file = open("C:\\Users\\Zed\\PycharmProjects\\ACL txt\\"+doc, 'r', encoding="utf8", errors='ignore')
text = file.read().strip()
file.close()
nopunc=[char for char in text if char not in punctuation]
nopunc=''.join(nopunc)
return [word for word in nopunc.split() if word.lower() not in english_stopwords]此代码块用于将所有文件名存储在我的文件夹中。
file_names=[]
for file in Path("ACL txt").rglob("*.txt"):
file_names.append(file.name)这段代码用于创建我正在工作的文档字典。
documents = {}
for i in file_names:
documents[i]=wordList(i)以上代码工作良好,速度快,但这段代码花费大量时间创建语料库,我如何改进这一点?
#create a corpus containing the vocabulary of words in the documents
corpus = [] # a list that will store words of the vocabulary
for doc in documents.values(): #iterate through documents
for word in doc: #go through each word in the current doc
if not word in corpus:
corpus.append(word) #add word in corpus if not already added此代码创建一个字典,用于存储语料库中每个单词的文档频率。
df_corpus = {} #document frequency for every word in corpus
for word in corpus:
k = 0 #initial document frequency set to 0
for doc in documents.values(): #iterate through documents
if word in doc.split(): #check if word in doc
k+=1
df_corpus[word] = k从2小时开始创建语料库并继续创建,请帮助我改进我的代码。这是我正在使用的viy9pCfJ数据集
发布于 2019-09-19 08:10:06
不如将语料库设置为https://docs.python.org/2/library/sets.html类型,而不是list?如果你也不需要额外的话。
corpus = set() # a list that will store words of the vocabulary
for doc in documents.values(): #iterate through documents
corpus.update(doc) #add word in corpus if not already addedhttps://stackoverflow.com/questions/57983960
复制相似问题