我有一个包含超过24,000,000行的大文件.txt
。现在我想要做一个字数统计,即计算每个单词及其相应的出现次数并将它们记录到一个新文件中。下面是我试图运行代码:使用python读写大文件
import gensim
class Corpus(gensim.corpora.TextCorpus):
def count_tokens(self):
word_count = 0
for text in self.get_texts():
word_count += len(text)
return word_count
def get_texts(self):
for filename in self.input:
yield open(filename).read().split()
def main():
corpus = Corpus(['somefile.txt'])
word_count = corpus.count_tokens()
text = open('somefile.txt').read().split()
with open('path_to_output', 'w') as f:
for word, _ in corpus.dictionary.token2id.items():
num_occur = text.count(word)
f.write('%s %d\n' % (word, num_occur))
if __name__ == '__main__':
main()
而且服务器挂起...我不知道是否有其他足够的方式这样做,或者我可以做什么改进?你如何用python读写真正大的文件?
使用类似系统的标记器 - 解析char char,并检查匹配项。当模棱两可时,继续查看下一个字符以决定是否有延续 – Uriel
'open(filename).read()。split()'完全读取文件,然后创建一个标记化版本:同时为内存的两倍。如果你只需要计数,Uriel方法可能是正确的。 –