在史前时期(Python 1.4),我们做到了:
fp = open('filename.txt')
while 1:
line = fp.readline()
if not line:
break
print line
Run Code Online (Sandbox Code Playgroud)
在Python 2.1之后,我们做了:
for line in open('filename.txt').xreadlines():
print line
Run Code Online (Sandbox Code Playgroud)
在我们在Python 2.3中获得方便的迭代器协议之前,可以做到:
for line in open('filename.txt'):
print line
Run Code Online (Sandbox Code Playgroud)
我见过一些使用更详细的例子:
with open('filename.txt') as fp:
for line in fp:
print line
Run Code Online (Sandbox Code Playgroud)
这是前进的首选方法吗?
[编辑]我得到了with语句确保关闭文件...但为什么不包含在文件对象的迭代器协议中?
我有一个带有许多线条的字符串.如何用一个for子句逐个阅读这些行?这是我想要做的,我在行中引用的textData var上得到一个错误for line in textData.
for line in textData
print line
lineResult = libLAPFF.parseLine(line)
Run Code Online (Sandbox Code Playgroud)
textData变量确实存在,我在下载之前打印它,但我认为预编译器正在解决错误.
TIA
丹尼斯
所以我有这个文本文件由数字和单词组成,例如像这样 - 09807754 18 n 03 aristocrat 0 blue_blood 0 patrician我想拆分它,以便每个单词或数字都会作为一个新行出现.
一个空白分隔符是理想的,因为我希望带有破折号的单词保持连接.
这是我到目前为止:
f = open('words.txt', 'r')
for word in f:
print(word)
Run Code Online (Sandbox Code Playgroud)
我不确定如何离开这里,我希望这是输出:
09807754
18
n
3
aristocrat
...
Run Code Online (Sandbox Code Playgroud) 我有一个大文本文件(约7 GB).我正在寻找是否存在阅读大文本文件的最快方法.我一直在阅读有关使用多种方法作为读取chunk-by-chunk以加快进程的过程.
例如,effbot建议
# File: readline-example-3.py
file = open("sample.txt")
while 1:
lines = file.readlines(100000)
if not lines:
break
for line in lines:
pass # do something**strong text**
Run Code Online (Sandbox Code Playgroud)
为了每秒处理96,900行文本.其他作者建议使用islice()
from itertools import islice
with open(...) as f:
while True:
next_n_lines = list(islice(f, n))
if not next_n_lines:
break
# process next_n_lines
Run Code Online (Sandbox Code Playgroud)
list(islice(f, n))将返回n文件的下一行列表f.在循环中使用它将为您提供大量n行的文件
在Python中,对于二进制文件,我可以这样写:
buf_size=1024*64 # this is an important size...
with open(file, "rb") as f:
while True:
data=f.read(buf_size)
if not data: break
# deal with the data....
Run Code Online (Sandbox Code Playgroud)
有了我想逐行阅读的文本文件,我可以这样写:
with open(file, "r") as file:
for line in file:
# deal with each line....
Run Code Online (Sandbox Code Playgroud)
这是简写:
with open(file, "r") as file:
for line in iter(file.readline, ""):
# deal with each line....
Run Code Online (Sandbox Code Playgroud)
这个成语记录在PEP 234中,但我找不到二进制文件的类似习惯用法.
我试过这个:
>>> with open('dups.txt','rb') as f:
... for chunk in iter(f.read,''):
... i+=1
>>> i
1 # 30 MB file, …Run Code Online (Sandbox Code Playgroud) 我试图计算100,000个向量的余弦相似度,并且这些向量中的每一个都有200,000个维度.
从阅读其他问题我知道memmap,PyTables和h5py是我处理这类数据的最佳选择,我目前正在使用两个memmaps; 一个用于读取矢量,另一个用于存储余弦相似性矩阵.
这是我的代码:
import numpy as np
import scipy.spatial.distance as dist
xdim = 200000
ydim = 100000
wmat = np.memmap('inputfile', dtype = 'd', mode = 'r', shape = (xdim,ydim))
dmat = np.memmap('outputfile', dtype = 'd', mode = 'readwrite', shape = (ydim,ydim))
for i in np.arange(ydim)):
for j in np.arange(i+1,ydim):
dmat[i,j] = dist.cosine(wmat[:,i],wmat[:,j])
dmat.flush()
Run Code Online (Sandbox Code Playgroud)
目前,htop报告说我正在使用224G的VIRT内存,而91.2G的RES内存正在稳步攀升.在我看来,在整个过程结束时,整个输出矩阵将存储在内存中,这是我试图避免的.
问:这是memmaps的正确用法,我在记忆有效的方式写入到输出文件(我的意思是,只有输入和输出文件的必要部分,即dmat[i,j]和wmat[:,i/j],存储在内存中)?
如果没有,我做错了什么,我该如何解决这个问题呢?
感谢您的任何建议!
编辑:我刚刚意识到htop报告的总体系统内存使用量为12G,所以它似乎正在起作用......那里有谁可以开导我?RES现在是111G ......
编辑2:memmap是从一维数组创建的,该数组由很多很长的小数组成,非常接近于0,形状符合所需的尺寸.然后memmap看起来像这样.
memmap([[ 9.83721223e-03, 4.42584107e-02, 9.85033578e-03, ...,
-2.30691545e-07, -1.65070799e-07, 5.99395837e-08],
[ 2.96711345e-04, -3.84307391e-04, 4.92968462e-07, ..., …Run Code Online (Sandbox Code Playgroud) 在Perl中,为了小写文本文件,我可以执行以下操作lowercase.perl:
#!/usr/bin/env perl
use warnings;
use strict;
binmode(STDIN, ":utf8");
binmode(STDOUT, ":utf8");
while(<STDIN>) {
print lc($_);
}
Run Code Online (Sandbox Code Playgroud)
并在命令行上: perl lowercase.perl < infile.txt > lowered.txt
在Python,我可以做lowercase.py:
#!/usr/bin/env python
import io
import sys
with io.open(sys.argv[1], 'r', 'utf8') as fin:
with io.open(sys.argv[2], 'r', 'utf8') as fout:
fout.write(fin.read().lower())
Run Code Online (Sandbox Code Playgroud)
并在命令行上: python lowercase.py infile.txt lowered.txt
Perl lowercase.perl与Python有lowercase.py什么不同?
是否输出输入并在输出时将其小写?或者它是否像Python一样读取整个文件lowercase.py?
有没有一种方法可以将输入流式传输到Python并逐字节输出降低的大小写或者通过char输出char?
有没有办法控制命令行语法,使其遵循Perl STDIN和STDOUT?比如python lowercase.py < infile.txt > lowered.txt?
我在一个非常大的列表中遇到了速度问题.我有一个包含很多错误和非常奇怪的文字的文件.我正在尝试使用difflib在我拥有的650,000个单词的字典文件中找到最接近的匹配项.下面这种方法效果很好,但非常慢,我想知道是否有更好的方法来解决这个问题.这是代码:
from difflib import SequenceMatcher
headWordList = [ #This is a list of 650,000 words]
openFile = open("sentences.txt","r")
for line in openFile:
sentenceList.append[line]
percentage = 0
count = 0
for y in sentenceList:
if y not in headwordList:
for x in headwordList:
m = SequenceMatcher(None, y.lower(), x)
if m.ratio() > percentage:
percentage = m.ratio()
word = x
if percentage > 0.86:
sentenceList[count] = word
count=count+1
Run Code Online (Sandbox Code Playgroud)
感谢您的帮助,软件工程甚至不是我的强项.非常感激.
我们在磁盘中有几个巨大的文件(大于RAM的大小).我想在python中逐行读取它们并在终端输出结果.我已经完成了[1]和[2],但我正在寻找不等到整个文件被读入内存的方法.
我将使用这两个命令:
cat fileName | python myScript1.py
python myScript2.py fileName
Run Code Online (Sandbox Code Playgroud)
python ×10
string ×3
file ×2
optimization ×2
chunking ×1
file-io ×1
filter ×1
iterator ×1
line ×1
list ×1
lowercase ×1
memory ×1
numpy ×1
performance ×1
perl ×1
python-2.7 ×1
python-3.x ×1
split ×1
text ×1