gpt4 book ai didi

python - 如何将多行输出到单行。我们也可以使用生成器来做到这一点吗?

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:40 25 4
gpt4 key购买 nike

请查看以下输出:-

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

关于python - 如何将多行输出到单行。我们也可以使用生成器来做到这一点吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46968092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com