gpt4 book ai didi

python - 如何在 Python 中将文本文件的每两行合并为一个字符串?

转载 作者:行者123 更新时间:2023-12-03 18:57:18 24 4
gpt4 key购买 nike

我想将文本文件的每两行合并为一个字符串,所有的字符串都分组到一个列表中。文本文件示例:

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/

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