如果第二行以特定单词开头,则追加两行文本

2024-05-16 22:32:25 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑具有下列内容的.txt文件:

Pinus ponderosa P. & C. Lawson
var. scopulorum Engelm.
[5,800] - [7,800] 9,200 ft. [May] - [Jun]. Needleleaf
evergreen tree, mesophanerophyte; nanophyll, sclerophyll.

我想将任何以var.开头的行附加到前一行

这是我的密码:

with open('myfile.txt', 'r') as f:
    txt = ''
    for line in f:
        line = line.replace('\n', '')
        if next(f)[:4] == 'var.':
            txt = '{}\n{} {}'.format(txt, line, next(f))

这会引发以下错误:

Traceback (most recent call last): File "<stdin>", line 5, in <module> StopIteration

预期产出为:

Pinus ponderosa P. & C. Lawson var. scopulorum Engelm.
[5,800] - [7,800] 9,200 ft. [May] - [Jun]. Needleleaf
evergreen tree, mesophanerophyte; nanophyll, sclerophyll.

Tags: txttreevarlinejunmayftevergreen
2条回答

这是一种方法

Ex:

with open(filename, 'r') as f:
    txt = ''
    for line in f:
        line = line.strip()
        if line.startswith('var.'):  #Use str.startswith
            txt += " " + line
        else:
            txt += "\n" + line

print(txt.strip())

输出:

Pinus ponderosa P. & C. Lawson var. scopulorum Engelm.
[5,800] - [7,800] 9,200 ft. [May] - [Jun]. Needleleaf
evergreen tree, mesophanerophyte; nanophyll, sclerophyll.

您可以一次完成它,而不是迭代行。此外,如果要编辑文件,请执行以下操作:

with open('myfile.txt', 'r') as f:
    txt = f.read()

txt = txt.replace('\nvar.', ' var.')

with open('myfile.txt', 'w') as f:
    f.write(txt)

相关问题 更多 >