![](/img/trans.png)
[英]Sorting lines by the second word on each line of text file, then displaying it
[英]Appending two text lines if the second line starts with a particular word
考虑一个包含以下内容的 .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.
开头的行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.
您可以一次性完成,而不是在线条上进行迭代。 另外,如果您想编辑文件:
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)
这是一种方法。
前任:
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.