0

我正在尝试在文本文件中创建一个文本列表,就像正在键入它一样。有点像这样:

T
Te
Tex
Text

我不知道如何解释它,所以这里有一个例子:

文本文件内容:

Line 1
Line 2
Line 3

第一行的列表将类似于:['L', 'Li', 'Lin', 'Line', 'Line ', 'Line 1', 'Line 1\n'].

完整的列表将是:[['L', 'Li', 'Lin', 'Line', 'Line ', 'Line 1', 'Line 1\n'], ['L', 'Li', 'Lin', 'Line', 'Line ', 'Line 2', 'Line 2\n'], ['L', 'Li', 'Lin', 'Line', 'Line ', 'Line 3']]

这是我当前的代码:

lines=open('foo.txt', 'r').readlines()
letters=[]
cnt=0
for line in lines:
    letters.append([])
    for letter in line:
        if len(letters[cnt]) > 0:
            letters[cnt].append(letters[cnt][len(letters[cnt])-1]+letter)
        else:
            letters[cnt].append(letter)
    cnt+=1

print letters

输出与上面的完整列表完全相同。

问题是这个代码在更大的文件上有点慢。有没有更快的方法来实现相同的输出?

4

4 回答 4

3
result = []
for line in open('foo.txt'):
    result.append([line[:i+1] for i in xrange(len(line))])
print result
于 2013-01-03T18:59:38.380 回答
2

使用list comprehension

In [66]: with open("data.txt") as f:
    print [[line[0:i+1] for i in range(len(line))] for line in f]
   ....:     
[['L', 'Li', 'Lin', 'Line', 'Line ', 'Line 1', 'Line 1\n'], 
 ['L', 'Li', 'Lin', 'Line', 'Line ', 'Line 2', 'Line 2\n'],
 ['L', 'Li', 'Lin', 'Line', 'Line ', 'Line 3', 'Line 3\n']]
于 2013-01-03T18:59:06.570 回答
1

这对于 Python 的 memoryviews 来说似乎是一个特别好的案例:使用它们时,您不会创建原始字符串的子字符串,而只会创建原始字符串的视图。行长于几个字符的大文件的性能提升应该是可观的。

results = []
with open("data.txt") as f:
    for line in f:
        letters = tuple(buffer(line, 0, i+1) for i in xrange(len(line)))
        results.append(letters)

如果不需要同时扩展所有前缀列表,可以考虑使用生成器。

注意:如果没有打印的计时,以下应该很难被击败;-)

with open("data.txt") as f:
    results = (buffer(line, 0, i+1) for line in f for i in xrange(len(line)))
于 2013-01-03T19:21:36.723 回答
1

这变慢的原因是因为您收集的只有冗余信息的大量列表。您是否真的需要这些列表,或者类似的东西也可以解决问题?

for line in lines:
    for i in range (0,len(line)-1):
        for j,letter in enumerate(line):
            print letter,
            if j>=i:
                print ''
                break

这输出

T 
T h 
T h i 
T h i s 
T h i s   
T h i s   i 
T h i s   i s 
T h i s   i s   
T h i s   i s   t 
T h i s   i s   t h 
T h i s   i s   t h e 
T h i s   i s   t h e   
T h i s   i s   t h e   f 
T h i s   i s   t h e   f i 
T h i s   i s   t h e   f i r 
T h i s   i s   t h e   f i r s 
T h i s   i s   t h e   f i r s t 
T h i s   i s   t h e   f i r s t   
T h i s   i s   t h e   f i r s t   l 
T h i s   i s   t h e   f i r s t   l i 
T h i s   i s   t h e   f i r s t   l i n 
T h i s   i s   t h e   f i r s t   l i n e 

我认为这就是您想要的(除了字母之间的空格,但我认为我们也可以以某种方式摆脱它们)。

于 2013-01-03T19:30:51.087 回答