作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想将文本文件的每两行合并为一个字符串,所有的字符串都分组到一个列表中。文本文件示例:
This is an example text file
containing multiple lines
of text, with each line
containing words made out of letters
我希望代码创建这样的字符串:
This is an example text file containing multiple lines
of text, with each line containing words made out of letters
我尝试了一些解决方案,但它们适用于 Python 2,但我正在使用 Python 3.9
with open(filePath) as text: # filePath is a variable asking for input by user, the user is required to type the file path of the .txt.file
lineCount = 0
firstLine = ""
secondLine = ""
lineList = []
finalResultList = []
for line in text: # Appends all the lines of the file
lineList.append(line)
for i in lineList: # Merges 2 lines at a time into a single one
if lineCount == 0:
firstLine = i
lineCount += 1
elif lineCount == 1:
secondLine = i
lineCount = 0
finalResult = str(str(firstLine) + " " + str(secondLine))
finalResultList.append(finalResult)
最佳答案
基于@sim 的评论:
with open('text.txt', 'r') as f:
lines = f.read().splitlines()
res = [' '.join(lines[i: i+2]) for i in range(0, len(lines), 2)]
请注意,这也适用于奇数行。
关于python - 如何在 Python 中将文本文件的每两行合并为一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65619175/
我是一名优秀的程序员,十分优秀!