Python:在不更改段落顺序的情况下反转文件每个段落中的单词?

问题描述 投票:0回答:1

我想通过反转text_in.txt文件中的单词来生成text_out.txt文件,如下所示:

text_in.txt具有两个段落如下:

Hello world, I am Here.

I am eighteen years old.

text_out.txt应该是这样的:

Here. am I world, Hello

old. years eighteen am I

我的代码是:

filein = open ('text_in.txt', 'r+')

fileout = open ('text_out.txt', 'w')


data = filein.read()

array1 = data.split(' ')

array1.reverse()

out1 = " " .join(array1)

fileout.write(out1)

我的结果是old. years eighteen am I \nHere. am I world, Hello

有人可以帮我解决吗?非常感谢!

python python-3.x python-requests reverse
1个回答
0
投票

你为什么不尝试这个?

filein = open ('text_in.txt', 'r+')

fileout = open ('text_out.txt', 'w')

for data in filein:

    array1 = data.split(' ')

    array1.reverse()

    out1 = " " .join(array1)

    fileout.write(out1)
© www.soinside.com 2019 - 2024. All rights reserved.