python - 如何将文本文档中的字符串转换为列表,并将列表分隔为python中的部分
问题描述
我在 .txt 文件中有以下单词,
examplex
exampley
examplea
exampleb
exampleg
exampleh
我想将它们转换成一个列表,然后将列表分成 2 组,以便看起来像输出。
输出:
examplex, exampley
examplea, exampleb
exampleg, exampleh
解决方案
输入.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
推荐阅读
- android - 从 recyclerview 中删除所有卡片视图,然后添加新卡片视图 - 添加相同的卡片视图
- android - 如何整体滚动android recyclerView而不是基于元素的焦点?
- java - 使用java中的while循环将用户输入转换为星号之类的密码
- docker - rm -rf 通过 Bitbucket 管道在容器内
- angularjs - 使用用户脚本将新的 AngularJS 控制器添加到主页
- processing - 处理 如何根据草图中的位置改变颜色?
- node.js - 如何在没有额外库的情况下在 linux 和/或 windows 中解压缩 zip 文件?
- javascript - Browsersync 在 Webpack 4 中随机崩溃/冻结?
- react-native - 使用相对 URL 的 fetch() 在 React Native 上失败
- oracle - 会话如何获得其初始时区