简体   繁体   English

如何修改 Python 中的迭代器的值?

[英]How do I modify the values of an iterator in Python?

As a side project, I'm making a basic HTML parser.作为一个附带项目,我正在制作一个基本的 HTML 解析器。 The HTML comes in as a string, and I make an iterator for it. HTML 作为字符串出现,我为它创建了一个迭代器。 I need to remove groups of whitespace at certain points, eg if the character is whitespace, I'd like to consume it, remove it, and advance one by one until I hit a non-whitespace character, where the function would stop.我需要在某些点删除空白组,例如,如果字符是空白,我想使用它,删除它,然后一个接一个地前进,直到遇到非空白字符,function 将停止。

Iterator setup:迭代器设置:

from more_itertools import peekable
chars = peekable("</        html    >")

For example:例如:

"</        html    >

...becomes: ...变成:

"</html    >"

I think the filter function is what you are looking for.我认为filter function 是您正在寻找的。

An example:一个例子:

import string
text = "</        html    >"

for c in filter(lambda x: x not in string.whitespace, text):
    print(c, end="")

The output is </html> output 是</html>

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

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