繁体   English   中英

Python 3.x:转到下一行

[英]Python 3.x : move to next line

我有一个小脚本,它从.html文件中提取一些文本。

f = open(local_file,"r")
for line in f:
    searchphrase = '<span class="position'
    if searchphrase in line:
        print("found it\n")

这对我来说很好(错误处理将在以后导入),我的问题是我要提取的文本在搜索短语之后跟随2行。 如何在.html文件中向下移动2行?

您可以通过在其上调用next()两次将f (可迭代)推进两行:

with open(local_file,"r") as f
    for line in f:
        searchphrase = '<span class="position'
        if searchphrase in line:
            print("found it\n")
            next(f) # skip 1 line
            return next(f)  # and return the line after that.

但是 ,如果你试图解析HTML,请考虑使用HTML解析器来代替 例如,使用BeautifulSoup

这对我很好:

f = open(local_file,"r")
found = -1
for line in f:
    if found == 2:
        print("Line: "+line);
        break
    elif found > 0:
        found += 1
    else:
        searchphrase = '<span class="position'
        if searchphrase in line:
            print("found it")
            found = 1

输入文件是:

bla
<span class="position">Hello</span>
blub
that's it
whatever

以及该计划的输出:

found it
Line: that's it

你可以将found重置为-1来搜索模式的更多出现,而不是调用break

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM