在test.txt中,我有兩行句子。如何在第一行顯示句子(多行)的行號?
The heart was made to be broken.
There is no surprise more magical than the surprise of being loved.
在代碼:
import re
file = open('test.txt','r')#specify file to open
data = file.readlines()
file.close()
print "---------------------------------------------------"
count = 0
for line in data:
line_split = re.findall(r'[^ \t\n\r, ]+',line)
count = count + 1
def chunks(line_split, n):
for i in xrange(0, len(line_split), n):
yield line_split[i:i+n]
separate_word = list(chunks(line_split, 8))
for i, word in enumerate(separate_word, 1):
print count, ' '.join(word)
print "---------------------------------------------------"
結果從代碼:
---------------------------------------------------
1 The heart was made to be broken.
---------------------------------------------------
2 There is no surprise more magical than the
2 surprise of being loved.
---------------------------------------------------
是否有僅在第一行顯示句的數量任何可能的方式?
期望的結果:
---------------------------------------------------
1 The heart was made to be broken.
---------------------------------------------------
2 There is no surprise more magical than the
surprise of being loved.
---------------------------------------------------
別t將標題添加到語言名稱 - 這是標籤的用途。 –