python - 将html字符串拆分为列表
问题描述
这是我的字符串:
'<.tag> xxxxx<./tag> <.tag>'
我想将其附加到列表中:
x=['<.tag>','xxxx','<./tag>','<.tag>']
解决方案
用于 re.findall
此目的
返回字符串中模式的所有非重叠匹配,作为字符串列表。从左到右扫描字符串,并按找到的顺序返回匹配项。如果模式中存在一个或多个组,则返回组列表;如果模式有多个组,这将是一个元组列表。结果中包含空匹配项
In [1]: a='<.tag> xxxxx<./tag> <.tag>'
In [2]: import re
In [4]: re.findall(r'<[^>]+>|\w+',a)
Out[4]: ['<.tag>', 'xxxxx', '<./tag>', '<.tag>']
In [5]: re.findall(r'<[^>]+>|[^<]+',a)
Out[5]: ['<.tag>', ' xxxxx', '<./tag>', ' ', '<.tag>']
In [17]: [i.strip() for i in re.findall(r'<[^>]+>|[^<]+',a) if not i.isspace()]
Out[17]: ['<.tag>', 'xxxxx', '<./tag>', '<.tag>']
推荐阅读
- assembly - i386指令“div ah”没有意义吗?
- reactjs - 我需要将浏览器路由器一分为二
- javascript - 你如何在闪亮的 htmlwidget (jsoneditor) 上调用 javascript 方法?
- java - 如何在 JAVA 中将十进制值转换为 24 小时时间格式
- java - 循环内的 printf
- html - 我的图片在 github 页面和 netlify 中都没有加载到我的站点中
- microsoft-graph-api - Microsoft Graph API - Odata 筛选器
- python - 具有嵌套 for 循环、条件和累加器的列表理解
- javascript - 在 Vue.js 中渲染双花括号 {{ }} 内的元素
- gitlab - Gitlab:无法使用 URL 下载工件