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

Python:在不改变段落顺序的情况下反转文件每个段落中的单词?,python,python-3.x,reverse,Python,Python 3.x,Reverse,我想通过反转text\u in.txt文件中的单词来生成一个text\u 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 with open("text_in.txt", 'r') as fin: read_data =

我想通过反转text\u in.txt文件中的单词来生成一个text\u 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
with open("text_in.txt", 'r') as fin:
    read_data = fin.read().splitlines()        #read and split into list of paragraphs

with open("text_out.txt", 'w') as fout:
    for p in read_data:
        words = p.split()                      #split words (by whitespace)
        fout.write(' '.join(reversed(words)))  #reverse the words
        fout.write('\n')
我的代码是:

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)
我的结果是
旧的。我十八岁了。我是世界吗,你好


有人能帮我解决吗?非常感谢

你为什么不试试这个

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

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

fileread = filein.readlines()

for data in fileread:

    array1 = data.split(' ')

    array1.reverse()

    out1 = " " .join(array1)

    fileout.write(out1)
这里的想法是逐行读取文件的内容(数据表示循环中的每一行),然后以追加模式反转并写入文件。
或者,您也可以使用
filein.readline()
一次读取一行。 以下是输出:

Here. am I world, Hello
old. years eighteen am I
你需要:

k = """Hello world, I am Here.
I am eighteen years old."""

x = k.split("\n")

x = [" ".join(i.split()[::-1]) for i in x]

k = "\n".join(x)
print(k)
输出:

Here. am I world, Hello
old. years eighteen am I
试试这个

filein=open('text_in.txt','r+'))
fileout=open('text\u out.txt','w')
data=filein.read()
out1=''#初始化空变量
对于data.split('\n'):在换行符的每个实例上分割\n
array1=每个。拆分(“”)#使用相同的代码
数组1.反向()
out1+=“”。join(array1)+“\n”#添加要拆分的新行
fileout.write(out1)#write

我给出了注释作为解释

代码中的问题是,您首先要颠倒段落的顺序,但实际上需要保留顺序。此外,我还将使用上下文管理器(
和open(…)
)进行文件处理,以确保自动打开和关闭文件

我会这样做:

Here. am I world, Hello

old. years eighteen am I
with open("text_in.txt", 'r') as fin:
    read_data = fin.read().splitlines()        #read and split into list of paragraphs

with open("text_out.txt", 'w') as fout:
    for p in read_data:
        words = p.split()                      #split words (by whitespace)
        fout.write(' '.join(reversed(words)))  #reverse the words
        fout.write('\n')

将字符串拆分\n,然后逐个反转所有行

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

data = filein.read()
array1 = data.split('\n')

for i in array1:
    array2 = i.split(' ')
    array2.reverse()
    out1 = " " .join(array2)
    fileout.write(out1)
    #print(out1)
用换行符(我假设换行符是一个新段落)拆分文本,并将每行倒转。