如何在Python中每2行拆分一次



我有一个输入,它的属性分布在行上,但是每个主题都有一个带有属性的换行符。所以我的输入是:

"subject n
property n
subject n
property n
etc"

我想把这个输入分成一个["subject\n property"、"subject\nproperty"等]的列表,但我对python还很陌生,似乎不能每隔一行就使用.splitlines()

有人知道我是否有办法用.splitlines()做到这一点,或者有更简单的替代方案吗?

您可以在n上进行拆分,然后将项目逐个重组:

可能是这样的:

s = "subject n property n subject n property n"
s = s.split()
res = []
for idx in range(0, len(s), 2):
res.append(f'{s[idx]} n {s[idx+1]}')   # you will have to ensure the number of elements is even, or protect against an Indexerror

res

输出:

['subject n property', 'subject n property']

灵感来自itertools:

def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)

https://docs.python.org/3.10/library/itertools.html

所以:

from itertools import zip_longest
s = [text.split('n')] * n # here n = 2
result = [ 'n'.join(lines).strip() for (*lines,) in zip_longest(*s, fill_value='') ]

(这个想法是通过执行以下操作:[text.split('n')] * n,创建一个包含n倍于相同迭代器的列表。使用zip_angest,您也可以使用该迭代器n次进行分组,然后每次迭代都会得到一个n行的元组。由于zip_lengest在同一迭代器上调用下一个,所以这些行相互跟随。最后一个strip((处理n_lines % n != 0的情况。处理最后一行的一种更优雅但稍长的方式是:result = [ 'n'.join(l for l in lines if l is not None).strip() for (*lines,) in zip_longest(*s) ](

另一种更简单的阅读方式:

s = text.split('n')
res = [ 'n'.join(s[i:i+2]) for i in range(0, len(s) // 2, 2) ]

一个功能风格的解决方案,您可以压缩列表切片

>>> text = "subject1nproperty1nsubject2nproperty2"
>>> lines = text.splitlines() 
>>> pairs = zip(lines[0::2], lines[1::2])
>>> list(pairs)
[('subject1', 'property1'), ('subject2', 'property2')]
>>> list(map("n".join, pairs))
['subject1nproperty1', 'subject2nproperty2']

我认为的一种方法是拆分所有内容,然后一次缝合2个,还有更好的方法

my_str = "subject n property n subject n property n etc"
all_splits = my_str.split('n')
ret = []
for i in range(0,len(all_splits),2):
ret.append(all_splits[i])
try:ret[-1]+="n"+all_splits[i+1]
except: pass
print(ret)
['subject n property ', ' subject n property ', ' etc']
s = "subject nproperty n subject nproperty n etc"
print(s.split(" n "))
#['subject nproperty', 'subject nproperty', 'etc']

我建议您使用splitlines((函数将字符串按每行拆分,并从获得的列表中,遍历每个偶数索引,将其添加到一个空字符串中,然后将其后面的索引添加到换行后的空字符串中。

看看这个代码:

def your_function(string): #Takes the combined string as input
list1 = string.splitlines()
list_to_return = []
for x in list1:
if list1.index(x) % 2 == 0:
list_to_return.append(f'{x} n {list1[list1.index(x) + 1]}')
return list_to_return

我相信这个代码符合您的要求。毫无疑问,这绝不是最简单或最有效的方法。但它确实完成了任务:(

使用re.sub即可。删除新行和空格('n\s'(,并在'property'后添加逗号,该逗号可以用作split:中的分隔符

my_str = "subject n property n subject n property"
my_str2 = re.sub('ns', '', my_str)
my_str3 = re.sub('property', 'property, ', my_str2)
my_str4 = re.sub('  subject', 'subject', my_str3)
my_str4.split(",")

输出为:

['subject property', 'subject property', ' ']

最新更新