簡體   English   中英

Python中如何將文本文件的每兩行合並為一個字符串?

[英]How to merge every two lines of a text file into a single string in Python?

我想將文本文件的每兩行合並為一個字符串,並將所有字符串分組到一個列表中。 文本文件示例:

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)]

請注意,這也適用於奇數行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM