请查看以下输出:-
Software_Engineer:
Networking
Software_Engineering
Computer_Graphics
Development
Design
Mechanical_Engineer:
Automata
(There is a new line character here)
我想要的输出应该是:-
Software_Engineer: Networking Software_Engineering Computer_Graphics Development Design
Mechanical_Engineer: Automata
到目前为止,我用 python 编写了以下代码:-
with open("split_module.txt") as f:
all_lines = f.readlines()
keys_col1 = []
values_col2 = []
for ids, values in enumerate(all_lines):
if ":" in all_lines[ids] and all_lines[ids+1] != "\n":
keys_col1.append(values.strip())
for value in keys_col1:
print(value)
我现在得到的输出为:-
Software_Engineer:
Software_Engineer:
Mechanical_Engineer:
这里,为什么“Software_Engineer:”重复两次,我怎样才能得到输出:-
Software_Engineer: Networking Software_Engineering Computer_Graphics Development Design
Mechanical_Engineer: Automata
请提出建议,因为我是 Python 新手...谢谢..!!
试试这个代码
fle=open("C:\Python27\projects\infile.txt")
fle2=open("C:\Python27\projects\outfile.txt",'w')
lst=fle.readlines()
for i in lst:
i=i.strip()
if i.endswith(':'):
fle2.write("\n")
fle2.write(i)
else:
fle2.write(i)
fle2.write(" ")
fle.close()
fle2.close()
outflie.txt的内容
Software_Engineer:Networking Software_Engineering Computer_Graphics Development Design
Mechanical_Engineer:Automata
我是一名优秀的程序员,十分优秀!