我需要为包含以下文本的文本文件计算Unigrams,BiGrams和Trigrams:
"囊性纤维化仅影响美国3万名儿童和青少年.吸入盐水雾可减少充满囊性纤维化患者呼吸道的脓液和感染,但副作用包括令人讨厌的咳嗽和严酷的味道.这就是结论在本周出版的"新英格兰医学杂志"上发表的两项研究."
我从Python开始并使用以下代码:
#!/usr/bin/env python
# File: n-gram.py
def N_Gram(N,text):
NList = [] # start with an empty list
if N> 1:
space = " " * (N-1) # add N - 1 spaces
text = space + text + space # add both in front and back
# append the slices [i:i+N] to NList
for i in range( len(text) - (N - 1) ):
NList.append(text[i:i+N])
return NList # return the list
# test code
for i in range(5):
print …Run Code Online (Sandbox Code Playgroud) 我正在使用在Ubuntu 9.04上运行的Python 2.6.2 [GCC 4.3.3].我需要使用Python脚本逐行读取大数据文件(~1GB,> 300万行).
我尝试了下面的方法,我发现它使用了非常大的内存空间(~3GB)
for line in open('datafile','r').readlines():
process(line)
Run Code Online (Sandbox Code Playgroud)
要么,
for line in file(datafile):
process(line)
Run Code Online (Sandbox Code Playgroud)
比方说,是否有更好的方法逐行加载大文件
几个建议给了我上面提到的方法并且已经尝试过,我试图看看是否有更好的方法来处理这个问题.到目前为止,我的搜索效果不佳.我感谢您的帮助.
p/s我已经使用了一些内存分析,Heapy并且在我正在使用的Python代码中没有发现内存泄漏.
2012年8月20日16:41(GMT + 1)更新
尝试了JF Sebastian,mgilson和IamChuckB建议的两种方法,(数据文件是一个变量)
with open(datafile) as f:
for line in f:
process(line)
Run Code Online (Sandbox Code Playgroud)
也,
import fileinput
for line in fileinput.input([datafile]):
process(line)
Run Code Online (Sandbox Code Playgroud)
奇怪的是他们都使用了〜3GB的内存,我测试的数据文件大小是765.2MB,由21,181,079行组成.我看到内存在时间上增加(大约40-80MB步长),然后稳定在3GB.
一个基本的疑问,是否有必要在使用后冲洗线?
我使用Heapy进行了内存分析,以便更好地理解这一点.
1级分析
Partition of a set of 36043 objects. Total size = 5307704 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 15934 44 1301016 …Run Code Online (Sandbox Code Playgroud) 从 python 中的给定字符串生成英语单词的所有可能组合。
输入:godaddy 输出:go、god、daddy、add、daddy
有什么好的图书馆吗?