猿问

Python:如何在不导入模块的情况下删除两个分隔符之间的文本

我搜索了很多线程,但它们都需要导入(BeautifulSoup、正则表达式)。输入是一个大字符串,其中多次出现分隔符(“<”、“>”) 我听说配对标签是一种很好的技术,但我不知道如何去做。


示例(非常小)输入:实际输入是整个 HTML 代码。


<!DOCTYPE html>

<html>

example

<head>

hello

<meta charset="utf-8">

example2

<meta/>

期望的输出:


example hello example2


紫衣仙女
浏览 122回答 2
2回答

MYYA

这是使用简单循环的简单易懂的方法:str = '<!DOCTYPE html><html>example<head>hello<meta charset="utf-8">'words = []temp = ""flag = 0for i in str:&nbsp; &nbsp; if i=="<":&nbsp; &nbsp; &nbsp; &nbsp; flag = 0&nbsp; &nbsp; &nbsp; &nbsp; if temp:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; words.append(temp)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; temp = ""&nbsp; &nbsp; elif i==">":&nbsp; &nbsp; &nbsp; &nbsp; flag=1&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; if flag==1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; temp += iprint(words)&nbsp; &nbsp;# prints ['example', 'hello']

陪伴而非守候

将变量初始化tag_depth为零。一次迭代一个字符的字符串。如果您看到一个<字符,则增加tag_depth,如果您看到一个>字符,则减少它。如果看到任何其他字符且tag_depth为零,则输出该字符。tag_depth = 0for c in mystring:&nbsp; &nbsp; if c == '<':&nbsp; &nbsp; &nbsp; &nbsp; tag_depth += 1&nbsp; &nbsp; elif c == '>':&nbsp; &nbsp; &nbsp; &nbsp; tag_depth -= 1&nbsp; &nbsp; elif tag_depth == 0:&nbsp; &nbsp; &nbsp; &nbsp; print(f"{c}", end=0)
随时随地看视频慕课网APP

相关分类

Python
我要回答