2014-10-31 66 views
-2

我有字數都在不同線路上例如列表的文件:輸出文件 - Python的

cat 
dog 
horse 
pig 
sheep 
mouse 

我想在Python是連接3個字一起寫的東西在一行中用空格隔開,並通過文件繼續輸出,例如:

cat dog horse 
pig sheep mouse 

這可能嗎?如果有人能幫助我,我將不勝感激。

+4

是的,這是可能的。如果你自己沒有開始並嘗試去做,通常人們不會傾向於幫助你。 – phantom 2014-11-01 00:00:33

+0

你的文件包含3的倍數,如果你有11行然後?即不是3的multipe。 – Hackaholic 2014-11-01 02:08:51

回答

-2
f=open('your_file','r') 
f=f.readlines() 
for x in [ " ".join(b[x-3:x]).replace('\n','') for x in range(1,len(b)) if x%3==0 ] 
    print x 
if len(f)%3 > 0: 
    print " ".join(b[-(len(b)%3):]).replace('\n','') 

例如:

a=['cat','dog','bat','hello','baby','stack','overflow','python','code','search','string'] 
output will be: 
'cat dog bat' 
'hello baby stack' 
'overflow python code' 
'search string' 

, 打開文件,讀取使用readlines()然後檢查了三個多內,並在國防部去年檢查文件,最後一個元素時,它不是多重化三

+0

爲什麼downvoting爲工作程序? – Hackaholic 2014-11-01 11:59:31

0

首先打開文件並將其讀入

file_contents = open("some_file.txt").read().split() 

那麼你打開一個文件寫入到

with open("file_out.txt","w") as f: 

然後你做魔術

 f.write("\n".join(" ".join(row) for row in zip(*[iter(file_contents)]*3))) 
+1

我總是喜歡你的代碼,但他是新手,沒有幫助他 – Hackaholic 2014-11-01 00:15:26

1

很容易! itertools.izip_longest

from itertools import izip_longest 

content = open("/tmp/words").read() 
step = 3 
# get line content and skip blank lines 
words = [line for line in content.split("\n") if line ] 

for group in izip_longest(*[iter(words)] * step, fillvalue=""): 
    print " ".join(group) # join by spaces 
+0

可能值得添加一個鏈接到itertools文檔,因爲這是石斑魚功能,你也應該使用打開文件或至少關閉它們後 – 2014-11-01 01:30:28

+0

謝謝@PadraicCunningham !我已經添加了一個鏈接到文檔。關於「與」關鍵字,我認爲這裏超出了範圍。 – felipsmartins 2014-11-01 02:39:43

+0

你爲什麼認爲使用上下文管理器超出了範圍? – 2014-11-01 10:25:38