【问题标题】:Reverse block of text every x lines in python在python中每x行反转文本块
【发布时间】:2018-01-22 09:59:15
【问题描述】:

我确定这是一个简单的 readlines 解决方案。我花了一些时间试图解决它但没有成功。

我有一段文字如下:

"This is the text 1"
0.0 2.0 2.0 2.0    
0.0 0.0 4.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0
"This is the text 2"
0.0 5.0 3.0 5.0    
0.0 0.0 6.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0

我正在努力将其更改为:

"This is the text 1"
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 4.0 0.0    
0.0 2.0 2.0 2.0
"This is the text 2"
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 0.0 0.0    
0.0 0.0 6.0 0.0    
0.0 5.0 3.0 5.0

非常感谢任何帮助。 谢谢

代码:

f = open("file.txt", "rb")
    s = f.readlines()
    f.close()
    f = open("newtext.txt", "wb")
    f.writelines(s[::-1])
    f.close()

返回整个 txt 文件倒置。

【问题讨论】:

  • 您需要向我们展示您目前编写的代码类型以及您遇到的问题。
  • 欢迎来到 Stack Overflow,请花点时间通过the welcome tour 了解您在这里的道路(同时也获得您的第一个徽章),阅读如何create a Minimal, Complete, and Verifiable example 并查看@987654323 @ 这样您就可以增加获得反馈和有用答案的机会。
  • @Chris 道歉,我当前的方法返回整个文件倒置,我需要将标题“这是文本 1”保留在同一个地方
  • @kazemakase 对格式表示抱歉,谢谢
  • @Qwerty 无需道歉。只要确保我做对了;)

标签: python numpy readlines


【解决方案1】:

这是在文本之间的行数始终保持一致的假设下工作的。

# Open file, split on newlines into a list
with open('file.txt') as f:
    data = f.read().splitlines()
# Break list into multiple lists 7 items long
# this covers the text and the 6 sets of numbers that follow
newlist = [data[i:i + 7] for i in range(0, len(data), 7)]

output = []
# Append the text, then iterate backwards across each list, stopping short of the text
for item in newlist:
    output.append(item[0])
    for x in item[:0:-1]:
        output.append(x)
# output to text file, adding a newline character at the end of each row
with open('newtext.txt', 'w') as f:
    for item in output:
        f.write('{}\n'.format(item))

【讨论】:

  • 这很好用!你能告诉我如何从左到右镜像数据吗?它是倒置的,但我认为我不需要镜像它
  • 我试过:for x in item[:0:-1]: output.append(x) for y in x[::-1]: output.append(y)
  • output.append(x[::-1])
  • 这行得通,但它也颠倒了“这是文本 2”,这就是为什么我在 x 中尝试 y 的原因。
  • 如果我有浮点数 5.3,我将如何确保 x[::-1] 不会返回 3.5?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-24
  • 2014-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多