2013-02-18 124 views
-1

用20個單詞的單個句子創建測試文件。讀取文件,然後插入回車符(\ n)並將測試寫入一個新的文本文件,該文件將由四行五個字組成。如何將單行分割爲多行

這是我迄今爲止

my_file = open("twentywords.txt", "r") 
temp_file = open("newfile.text", "w") 

i = 1 
for words in my_file: 
    if i%5 == 0: 
     print(words, file = temp_file) 
    i = i + 1 

我們還沒有學會複雜的工具又是那麼保持它的簡單燉

回答

0

使用.split(),使單詞的列表:

>>> 'This is a test'.split() 
['This', 'is', 'a', 'test'] 

不帶參數調用.split()可以使所有空白字符分割字符串。在整個文件作爲一個字符串

>>> '-'.join(['This', 'is', 'a', 'test']) 
'This-is-a-test' 
>>> ['This', 'is', 'a', 'test'][1:3] 
['is', 'a'] 
+0

,但我需要使用\ n工具 – user2016535 2013-02-18 02:56:40

0
with open('infile.txt') as f_in, open('outfile.txt', 'w') as f_out: 
    f_out.write('\n'.join(f_in.read().split())) 
0

閱讀:

從那裏,你可以用切片和.join()。使用空格作爲分隔符分割字符串。將數組元素寫入輸出文件。在每個第五個元素處插入一個\ n。

+0

my_file =打開( 「twentywords.txt」, 「R」) temp_file =打開(「newfile中。 (listme,file = temp_file) listme = my_file.readline()我不明白你的意思是插入一個\ n listme = listme.split(「」) print(listme,file = temp_file) – user2016535 2013-02-18 03:24:00

0

非常難懂,但oneliner:

mystring = my_file.read() 
print "\n".join(([" ".join(line) for line in zip(*(iter(mystring.split()),) * 5)]))