2015-11-16 10 views
-1

我有一個文本文件,基本上它是一羣即將去做東西的角色,但我一直在麻煩分裂它。如何分段文本文件?

它看起來像這樣:

1 2 3 4 5 6 7 8 
9 10 11 12 13 14 

15 16 17 18 19 20 
21 22 23 24 25 26 27 
28 29 30 31 32 33 34 35 36 37 

39 40 
41 42 

我想通過「段落」分裂,然後從那裏通過每一行。我知道如何閱讀函數和一切,但我一直在嘗試的一切都沒有工作,比如做split('\ n \ n')。有任何想法嗎?

+0

如果你做'分裂( '\ n \ n')'會發生什麼? –

+0

我只是把所有的數字全部放在一個字符串中,並且'\ n'在其中。這很奇怪 – ekw95

+3

讀取整個文件,然後像'filobj.read()split('\ n \ n')''split''\ n \ n')' –

回答

1

這實際上是簡單得多比你使它:

10. Read each line in and append them together as long 
    as the next line is not empty. 
    When you do encounter a blank line, 
    split the current "paragraph" with ` `. 

20. Goto 10 
1

這看起來像你想要什麼:

txt=open("nums.txt").read() 
[[x for x in ilist if len(x) > 0] for ilist in map(lambda x : x.split("\n"),txt.split("\n\n"))] 

[['1 2 3 4 5 6 7 8 ', '9 10 11 12 13 14 '], ['15 16 17 18 19 20', '21 22 23 24 25 26 27', '28 29 30 31 32 33 34 35 36 37'], ['39 40', '41 42']]

如果你想他們都爲整數,然後:

map (lambda x : map(lambda x :reduce (lambda z,y: z+[int(y)] if y.isdigit() else z,x.split(),[]),x),[[x for x in ilist if len(x) > 0] for ilist in map(lambda x : x.split("\n"),txt.split("\n\n"))]) 

這給O/P:

[[[1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14]], [[15, 16, 17, 18, 19, 20], [21, 22, 23, 24, 25, 26, 27], [28, 29, 30, 31, 32, 33, 34, 35, 36, 37]], [[39, 40], [41, 42]]]