Python:如何合并显示为句子和显示行号

时间:2012-05-05 20:25:46

标签: python

import re
line = "the heart was made to be broken"
line_split2 = re.split(r'[ \t\n\r, ]+',line)

def chunks(line_split2, n):
    for i in xrange(0, len(line_split2), n):
        yield line_split2[i:i+n]

separate_word = list(chunks(line_split2, 3))

import pprint
pprint.pprint(separate_word)

count = 0
for lines in separate_word:
    count = count + 1
    print count

我正在尝试合并列表以显示为句子并在它们前面显示行号。

1 the heart was
2 made to be
3 broken

有什么建议吗?

4 个答案:

答案 0 :(得分:2)

您可以使用enumerate()

s = ['the heart was', 'made to be', 'broken']

for i, line in enumerate(s, 1):
    print '%d %s' %(i, line)

1 the heart was
2 made to be
3 broken

有关枚举的详细信息,请参阅http://docs.python.org/library/functions.html#enumerate

答案 1 :(得分:1)

使用enumerate()跟踪您所在的行:

for i, word in enumerate(separate_word, 1):
    print i, ' '.join(word)

> 1 the heart was
> 2 made to be
> 3 broken

答案 2 :(得分:1)

无需编写自己的chunks函数。使用itertools documentation中的grouper食谱,然后对结果使用enumerate

enumerate(grouper(3, line_split2), start = 1)

以下是grouper的代码:

from itertools import izip_longest

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

答案 3 :(得分:0)

只需在for循环中使用join

import re
line = "the heart was made to be broken"
line_split2 = re.split(r'[ \t\n\r, ]+',line)

def chunks(line_split2, n):
 for i in xrange(0, len(line_split2), n):
    yield line_split2[i:i+n]

separate_word = chunks(line_split2, 3)


count = 0
for lines in separate_word:
    count = count + 1
    print count, " ".join(map(str,lines))

1 the heart was
2 made to be
3 broken