在 Python 中删除一些换行符但不是全部

remove some newline but not all in Python

我有这种格式的数据

Picture
'#Type'
'10', '10'
000000000000000
110000110110000
Picture2
'#Type2'
'10', '10'
000000000000000
110000111110000

我可以使用

读取文件
sourcefile.read().splitlines() 

但是第 4 行和第 5 行将是列表中的两个项目。例如,列表将是

[picture],[#type],[10,10],[000000000000000],[110000110110000],...

但我的目标是连接 [000000000000000][110000110110000],即第 4 行和第 5 行,使它们成为一项。最终结果类似于

[Picture],
['#Type'],
['10', '10'],
[000000000000000110000110110000]

我怎样才能做到这一点?更好的是,我怎样才能在嵌套列表中将它们 4 作为一个组?非常感谢。

如果每张图片总是有 4 行,那么您可以像现在一样拆分这些行 - 然后合并每第 3 行和第 4 行以获得结果

您可以在数组完成后重新迭代它。

arr = sourcefile.read().splitlines() 

获得数组后,您可以提取长度超过 9 个字符的输入

arrOfLargeNumbers = filter(lambda x: len(x) > 9, arr)

然后从数组中删除旧的并添加新的

arr.remove(arrOfLargeNumbers[0])
arr.remove(arrOfLargeNumbers[1])
arr.append(f'{arrOfLargeNumbers[0]}{arrOfLargeNumbers[1]}'

你可以尝试以下方法吗:

with open('data.txt', 'r') as infile:
    data = infile.read()
split_data = data.split('\n')
req_list = range(3, len(split_data), 5)
flag = False
for ind, val in enumerate(split_data):
    if flag:
        print([split_data[ind-1] + val])
        flag = False
        continue
    if ind not in req_list:
        print([val])
    else:
        flag = True

输出:

['Picture']
["'#Type'"]
["'10', '10'"]
['000000000000000110000110110000']
['Picture2']
["'#Type2'"]
["'10', '10'"]
['000000000000000110000111110000']
with open("path_to_your_input_file", "r") as f:
lines = [line.rstrip() for line in f.readlines()]
new_lines = []
last_was_digit = 0
for i, line in enumerate(lines):
    if line.isdigit() and last_was_digit == 0:
        new_lines.append(["".join([line, lines[i+1]])])
        last_was_digit = 1
    elif last_was_digit == 1:
        last_was_digit = 0
    else:
        new_lines.append([line])

所以这段代码通过从文件中读取来完成工作。它不优雅,但它有效。

输出:

> [['Picture'], ["'#Type'"], ["'10', '10'"], ['000000000000000110000110110000']
> ['Picture2'], ["'#Type2'"],["'10', '10'"], ['00000000000000011000011111000']]