您可以使用groupby
和count
从itertools
模块以及list comprehension
。
这个答案有点不好意思,但是要诀窍。请参阅评论以更好地理解背后的逻辑。
我假设你的投入,你是在一个名为my_input_file
文件给出了输入和输出文件被称为output_file
:
from itertools import groupby, count
# Read the file and split by the space between Value and its number
# Leave the case where the empty string '' exists without splitting its spaces
with open("my_input_file", 'r') as f:
data = (k.split() if k != '' else k for k in f.read().splitlines())
# Group the fields splitted, which are lists, in data
# And separate them by the field where the string 'Blank' exists
sub = [list(v) for _, v in groupby(data, lambda x: isinstance(x, list))]
final = []
for elm in sub:
# if the lenght of the grouped elements is > 1
if len(elm) >1:
# Convert the number of the values into an int
# For further calculations
dd = map(lambda x: [x[0], int(x[1])], elm)
# Group the consecutive numbers of elem
for _,v in groupby(dd , lambda x,y=count(): x[1] - next(y)):
# If there is a consecutive numbers
bb = list(v)
if len(bb) >1:
# Conveert them into strings. Then, append the first and the final one to the final list
final.append(' '.join(map(str, bb[0])) + ',' + ' '.join(map(str, bb[-1])))
# If there is'nt any consecutif numbers. Append the element to the final list
else:
final.append(" ".join(map(str, bb[0])))
# create the output file
with open("output_file", 'a') as f:
for k in final:
f.write(k + '\n')
这段代码输出包含一个文件:
Value 1,Value 3
Value 4,Value 5
Value 6,Value 8
Value 9,Value 11
Value 12,Value 13
测试此代码,并留下您的反馈,如果您有任何或可能,请报告错误,如果你发现任何他们。
编辑:
根据上次编辑。
如果输入的文件是:
What Test
Makes No Sense
is This
My name
Is Sample 123
Your Name
is ABC 2134
What is you
technical question don't know
name?
诀窍,就是这么简单。你可以做这样的事情,只有groupby
利用itertools
模块:
from itertools import groupby
with open("my_input_file", 'r') as f:
data = f.read().splitlines()
final = [list(v) for _, v in groupby(data, lambda x: x != '')]
with open("ouput_file", 'a') as f:
for k in final:
if k != ['']:
f.write(k[0] + ',' + k[-1] + '\n')
而且,你的输出文件将是:
What Test ,is This
My name ,Is Sample 123
Your Name ,is ABC 2134
What is you ,name?
你迄今为止编写任何代码? (请将其张贴出来;因为SO不是编码服务,所以你写的问题是无关紧要的。) – DyZ
一行:''\ n'.join(['{},{}'。format(l [ ('\ n \ n')]]])' – dawg