2012-04-18 51 views
1

我有一個字符串:格式化行Python中打破

f = open("file.txt", r) 
message = f.read() 

print message 
>>> "To: email\ntitle: add title here\nDescription: whatever here\n" 

我可以做分割字符串:

f_email, f_title, f_description, blank = message.split('\n') 

但是,當我有這樣的消息,問題出現了:

"To: email\ntitle: add title here\nDescription: first line\nSecond line\nthirdline\n" 

當我拆分字符串時,它也分解描述。我曾嘗試過:

f_email, f_title, f_description, blank = message.split('\n',4) 

但是,顯然返回ValueError是因爲它正在分裂更多4 \ n's。

有什麼建議嗎?

+0

如果「要」和「標題」總是在沒有內部換行符自己行,你可以只劈在' \ n',第一個元素是電子郵件,第二個標題,併爲身體做'\ n'.join(therest)'? – 2012-04-18 13:42:00

+0

也許你可以逐行閱讀文件。 – Akavall 2012-04-18 13:45:32

回答

4

當您運行.split('\n')時,您將返回一個列表。而不是分配變量時拆分,可以拉出來的名單:

tokens = message.split('\n') 
f_email = tokens[0] 
f_title = tokens[1] 
f_description = tokens[2] 

這可以由通過檢查列表的大小不那麼脆弱。如果你知道它至少需要三個要素,您可以:

assert(len(tokens)>=3) 

另一種方式來解決這個問題是包裝的事情了一個try/except塊:

tokens = message.split('\n') 
try: 
    f_description = tokens[2] 
except: 
    f_description = None 

這樣,你可以處理一個較短的清單案例你喜歡的確切方式!

+0

非常感謝! – Neeran 2012-04-18 13:43:58

4

@Hooked爲Python2提供了一個很好的答案。 由於Python3 *作品也爲元組拆包,你可以這樣做:

f_email, f_title, *f_description = tokens 

細節在PEP 3132

+0

Arg,我剛剛發佈了這個;)+1,這是3.x用戶的不錯解決方案。 – 2012-04-18 13:46:12

+0

爲了完整性,您可以使用'\ n's加入f_description的元素來重新獲得原始描述字符串。 – covertCoder 2012-04-18 13:48:54

+0

此外,本着這種精神的解決方案,可以通過將'* tokens'傳遞給進行處理的方法來適應Python2。 – 2012-04-18 13:57:58

1

如果你不想使用的文本作爲一個整體,而不是在3 .X使用漂亮的圖示拆包,你可以簡單地做這樣的:

email = None 
title = None 
description = "" 
with open("test.txt", "r") as f: 
    for number, line in enumerate(f): 
     if number == 0: 
      email = line.strip() 
     elif number == 1: 
      title = line.strip() 
     else: 
      description += line 
+0

+1:非常感謝您的幫助,但如果我從文件中獲得很長的字符串,代碼可能會顯得有點長。 – Neeran 2012-04-18 14:06:16

1

當您使用message.split(「\ n」,2)你會得到三個部分組成:第一行,第二行和剩餘線在一個。

使用這種形式:

f = open("file.txt") 
f_email, f_title, f_description = f.read.split('\n', 2) 
f.close() 

或者這樣:

f = open("file.txt") 
f_email = f.readline() 
f_title = f.readline() 
f_description = f.read() 
f.close()