首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建一个包含单词词汇的语料库

问创建一个包含单词词汇的语料库
EN

Stack Overflow用户
提问于 2019-09-18 01:48:01
回答 1查看 1K关注 0票数 0

我正在为我的文档字典中的所有单词计算inverse_document_frequency,我必须根据查询得分显示排名前5的文档。但是我在创建包含文档中单词词汇表的语料库时陷入了循环。请帮助我改进我的代码。这段代码用于读取我的文件,删除标点符号和停止文件中的单词。

代码语言:javascript
复制
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]

此代码块用于将所有文件名存储在我的文件夹中。

代码语言:javascript
复制
file_names=[]
for file in Path("ACL txt").rglob("*.txt"):
file_names.append(file.name)

这段代码用于创建我正在工作的文档字典。

代码语言:javascript
复制
documents = {}
for i in file_names:
documents[i]=wordList(i)

以上代码工作良好,速度快,但这段代码花费大量时间创建语料库,我如何改进这一点?

代码语言:javascript
复制
#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

此代码创建一个字典,用于存储语料库中每个单词的文档频率。

代码语言:javascript
复制
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数据集

EN

回答 1

Stack Overflow用户

发布于 2019-09-19 08:10:06

不如将语料库设置为https://docs.python.org/2/library/sets.html类型,而不是list?如果你也不需要额外的话。

代码语言:javascript
复制
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 added
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57983960

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档