无法在Python中读取完整文本文件
我在用Python读取一个文件时遇到了问题。
我正在读取的文件大小是90MB。在Word中打开时,显示总字数大约是1400万。但是当我在Python中读取这个文件时,它告诉我文件的字数大约是900万(8,915,710个单词)。
当我通过Python命令检查文件中的最后100个单词时,
print "The length of the Corpus is ", len(tokens), tokens[-100:]
我只看到原始文件中间部分的单词。
我使用的是64位的Windows操作系统和32位的Python版本。
我的电脑配置是:i7处理器,1.8GHz,6GB内存。
我想知道为什么Python读取不到8,915,710个单词以外的内容。
谢谢。
代码:
f = open('testtext.txt')
raw = f.read()
corp = lowercase(raw)
tokens = nltk.word_tokenize(corp)
print "The number of words is ", len(tokens), tokens[-100:]
print "corp ", len(corp)
print "raw ", len(raw)
我得到了以下答案:
>> The number of words is 8915710
>> corp 53322476
>> raw 53322476
2 个回答
0
试着把这个文件当作二进制文件来处理:
f = open('file.txt', "rb")
chunkSize = 1024
dataChunk = f.read(chunkSize)
while len(dataChunk):
processData(dataChunk)
dataChunk = f.read(chunkSize)
1
把这一行替换成:
f = open('testtext.txt')
用这一行替换:
f = open('testtext.txt', 'rb')