每行输出三个单词的文件 - Python

-2 投票
3 回答
779 浏览
提问于 2025-04-30 23:30

我有一个文件,里面有很多单词,每个单词都在不同的行上,比如:

cat
dog
horse
pig
sheep
mouse

我想用Python写个程序,把每三行单词合并成一行,中间用空格隔开,然后继续处理文件,最后的输出大概是这样的:

cat dog horse
pig sheep mouse

这样做可能吗?如果有人能帮我,我会非常感激。

暂无标签

3 个回答

-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

首先,你要打开一个文件并把里面的内容读出来。

 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

这很简单!你可以使用 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

撰写回答