【问题标题】:Output file with three words on each line - Python每行包含三个单词的输出文件 - Python
【发布时间】:2014-10-31 23:57:32
【问题描述】:

我有一个文件,其中包含不同行的单词列表,例如:

cat
dog
horse
pig
sheep
mouse

我想在 python 中写一些东西,将 3 个单词连接在一行中,用空格分隔并继续通过文件,示例输出如下所示:

cat dog horse
pig sheep mouse

这可能吗?如果有人可以帮助我,我将不胜感激。

【问题讨论】:

  • 是的,这是可能的。如果您还没有自己开始并尝试这样做,人们通常不会倾向于帮助您。
  • 您的文件包含 3 的倍数,如果您有 11 行那么?即不是3的倍数??

标签: python python-2.7 split newline


【解决方案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

【讨论】:

  • 可能值得添加指向 itertools 文档的链接,因为这是 grouper 功能,您还应该使用 with 打开文件或至少在之后关闭它们
  • 谢谢@PadraicCunningham!我添加了一个文档链接。关于“with”关键字,我认为它超出了这里的范围。
  • 为什么你认为使用上下文管理器超出了范围?
【解决方案2】:

首先你打开文件并读入

 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】:
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,最后一个元素不是三的倍数时

【讨论】: