首页 > 解决方案 > 如何将文本文档中的字符串转换为列表,并将列表分隔为python中的部分

问题描述

我在 .txt 文件中有以下单词,

examplex
exampley
examplea
exampleb
exampleg
exampleh

我想将它们转换成一个列表,然后将列表分成 2 组,以便看起来像输出。

输出:

 examplex, exampley
 examplea, exampleb
 exampleg, exampleh

标签: pythonarrayslisttextformat

解决方案


输入.txt

examplex
exampley
examplea
exampleb
exampleg
exampleh

转换.py

r = open("input.txt", "r")
input = r.read()

output = ""
pair = 0

for i in input:
    # Every other '\n' character don't skip a line
    if(i == "\n" and pair % 2 == 0):
        output += ", "
        pair += 1
    # increment pair, but still add newline
    elif(i == "\n"):
        output += i 
        pair += 1
    else:
        output += i 

r.close()

# Write to output.txt
w = open("output.txt", "w")
w.write(output)
w.close()

输出.txt

examplex, exampley
examplea, exampleb
exampleg, exampleh

推荐阅读