Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
输出文件,每行三个字-Python_Python_Python 2.7_Split_Newline - Fatal编程技术网

输出文件,每行三个字-Python

输出文件,每行三个字-Python,python,python-2.7,split,newline,Python,Python 2.7,Split,Newline,我有一个文件,其中有一个单词列表,所有单词都在不同的行上,例如: cat 狗 马 猪 羊 老鼠 我想用python编写一些东西,将3个单词连接在一行中,以空格分隔,并继续遍历文件,示例输出如下: 猫狗马 猪羊鼠 这可能吗?如果有人能帮助我,我将不胜感激 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

我有一个文件,其中有一个单词列表,所有单词都在不同的行上,例如:

cat
狗
马
猪
羊
老鼠
我想用python编写一些东西,将3个单词连接在一行中,以空格分隔,并继续遍历文件,示例输出如下:

猫狗马 猪羊鼠 这可能吗?如果有人能帮助我,我将不胜感激

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()
读取文件,然后检查三个元素的倍数,最后检查最后一个元素的mod,如果不是三个元素的倍数

 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)))
很简单!:


是的,这是可能的。如果您还没有亲自开始并尝试这样做,人们通常不会愿意帮助您。您的文件包含3的倍数,如果您有11行,那么??i、 e不是3的多倍??我总是喜欢你的代码,但他是新手,对他没有帮助可能值得添加到itertools文档的链接,因为这是grouper函数,你还应该使用来打开文件或至少在hanks@padraickenningham之后关闭它们!我添加了一个指向doc的链接。关于“with”关键字,我认为它超出了范围。为什么您认为使用上下文管理器超出了范围?
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