2014-10-31 67 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