【问题标题】:How optimize word counting in Python?如何优化 Python 中的字数统计?
【发布时间】:2014-04-03 22:06:30
【问题描述】:

我正在着手编写代码以对文本进行语言分析。我使用 Python 和 NLTK 库。问题是单词的实际计数占用了我的 CPU(iCore5、8GB RAM、macbook air 2014)的近 100%,并且在我关闭进程之前运行了 14 小时。如何加快循环和计数?

我从三个瑞典语 UTF-8 格式、制表符分隔的文件 Swe_Newspapers.txt、Swe_Blogs.txt、Swe_Twitter.txt 中创建了一个 NLTK 语料库。它工作正常:

import nltk
my_corpus = nltk.corpus.CategorizedPlaintextCorpusReader(".", r"Swe_.*", cat_pattern=r"Swe_(\w+)\.txt")

然后我将一个每行一个单词的文本文件加载到 NLTK 中。这也很好用。

my_wordlist = nltk.corpus.WordListCorpusReader("/Users/mos/Documents/", "wordlist.txt")

我要分析的文本文件 (Swe_Blogs.txt) 具有这种结构,并且可以很好地解析:

Wordpress.com   2010/12/08  3   1,4,11  osv osv osv …
bloggagratis.se 2010/02/02  3   0   Jag är utled på plogade vägar, matte är lika utled hon.
wordpress.com   2010/03/10  3   0   1 kruka Sallad, riven

编辑:生成计数器的建议如下,不起作用,但可以修复:

counter = collections.Counter(word for word in my_corpus.words(categories=["Blogs"]) if word in my_wordlist)

这会产生错误:

IOError                                   Traceback (most recent call last)
<ipython-input-41-1868952ba9b1> in <module>()
----> 1 counter = collections.Counter(word for word in my_corpus.words("Blogs") if word    in my_wordlist)
       /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nltk/corpus/reader/plaintext.pyc in words(self, fileids, categories)
182     def words(self, fileids=None, categories=None):
183         return PlaintextCorpusReader.words(
--> 184             self, self._resolve(fileids, categories))
185     def sents(self, fileids=None, categories=None):
186         return PlaintextCorpusReader.sents(

                /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- packages/nltk/corpus/reader/plaintext.pyc in words(self, fileids, sourced)
 89                                            encoding=enc)
 90                            for (path, enc, fileid)
 ---> 91                            in self.abspaths(fileids, True, True)])
 92 
 93 
 /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nltk/corpus/reader/api.pyc in abspaths(self, fileids, include_encoding, include_fileid)
165             fileids = [fileids]
166 
--> 167         paths = [self._root.join(f) for f in fileids]
168 
169         if include_encoding and include_fileid:  

/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/      lib/python2.7/site-packages/nltk/data.pyc in join(self, fileid)
174     def join(self, fileid):
175         path = os.path.join(self._path, *fileid.split('/'))
--> 176         return FileSystemPathPointer(path)
177 
178     def __repr__(self):

/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/  lib/python2.7/site-packages/nltk/data.pyc in __init__(self, path)
152         path = os.path.abspath(path)
153         if not os.path.exists(path):
--> 154             raise IOError('No such file or directory: %r' % path)
155         self._path = path

IOError: No such file or directory: '/Users/mos/Documents/Blogs'

解决方法是将 my_corpus(categories=["Blogs"] 分配给一个变量:

blogs_text = my_corpus.words(categories=["Blogs"])

当我尝试在语料库 (115,7 MB) 的博客中的单词列表中计算每个单词(大约 20K 单词)的所有出现次数时,我的计算机有点累了。如何加快以下代码的速度?它似乎工作,没有错误消息,但它需要> 14小时才能执行。

import collections
counter = collections.Counter()

for word in my_corpus.words(categories="Blogs"):
    for token in my_wordlist.words():
        if token == word:
            counter[token]+=1
        else:
            continue

非常感谢任何有助于提高我的编码技能的帮助!

【问题讨论】:

    标签: python-2.7 optimization nlp nltk


    【解决方案1】:

    看来你的双循环可以改进:

    for word in mycorp.words(categories="Blogs"):
        for token in my_wordlist.words():
            if token == word:
                counter[token]+=1
    

    这样会更快:

    words = set(my_wordlist.words()) # call once, make set for fast check
    for word in mycorp.words(categories="Blogs"):
        if word in words:
            counter[word] += 1
    

    这使您从执行len(my_wordlist.words()) * len(mycorp.words(...)) 操作到更接近len(my_wordlist.words()) + len(mycorp.words(...)) 操作,因为构建集合是O(n),并且检查一个单词是否在集合中平均是O(1)。

    您也可以直接从可迭代对象构建Counter,正如两位炼金术士指出的那样:

    counter = Counter(word for word in mycorp.words(categories="Blogs") 
                      if word in words)
    

    【讨论】:

    • 我不知道 NTLK 库,但您和 OP 是否有理由手动填充 Counter?通常你打电话给Counter(iterable),我假设你可以在这里打电话Counter(my_wordlist.words())?
    • @Two-BitAlchemist 看起来确实很奇怪。我只是在研究 nltk 语料库是否提供内置的成员资格检查,但我认为 Counter(word for word in ... if word in ...) 会起作用
    • 我还会检查每个列表中有多少项目,以了解您正在处理多少数据。如果您正在扫描 20,000 个单词,而您的文本正文有 100,000 个单词,那么您实际上是在进行 10 亿次操作。你的情况可能比这更糟糕。
    • @ojblass 对 set 的成员资格检查平均为 O(1),因为它是基于哈希的(请参阅 wiki.python.org/moin/TimeComplexity)
    • 我接受了上述两个建议,但需要修复以使计数器膨胀的@Two-Bit Alchemist 优化工作。我已经编辑了错误消息和问题中的代码修复。
    【解决方案2】:

    关于如何使用 Python 正确计算单词,您已经得到了很好的答案。问题是它仍然会很慢。如果您只是探索语料库,使用 UNIX 工具链可以更快地获得结果。假设您的文本被标记化,这样的事情会按降序为您提供前 100 个标记:

    cat Swe_Blogs.txt | cut --delimiter='\t' --fields=5 | tr ' ' '\n' | sort | uniq -c | sort -nr | head -n 100
    

    【讨论】:

    • 谢谢 - 这真的很有趣!
    • 是的,UNIX 终端是你的朋友!
    猜你喜欢
    • 1970-01-01
    • 2023-01-04
    • 1970-01-01
    • 1970-01-01
    • 2022-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    相关资源
    最近更新 更多