python - 使用 Python 对 HTML 源代码进行标记和标记

标签 python html token

我有一些带注释的 HTML 源代码,其中的代码与使用 requests 得到的代码类似,注释是带有标签项开始处的字符索引的标签,

例如,源代码可以是:

<body><text>Hello world!</text><text>This is my code. And this is a number 42</text></body>

标签可以是例如:

[{'label':'salutation', 'start':12, 'end':25},
 {'label':'verb', 'start':42, 'end':45},
 {'label':'size', 'start':75, 'end':78}]

分别指“Hello world”、“is”和“42”。我们事先知道标签不重叠。

我想处理源代码和注释以生成适合 HTML 格式的标记列表。

例如,它可以在这里生成如下内容:

['<body>', '<text>', 'hello', 'world', '</text>', '<text>', 'this', 'is', 'my', 'code', 'and', 'this', 'is', 'a', 'number', '[NUMBER]', '</text>', '</body>']

此外,它必须将注释映射到标记化,生成与标记化长度相同的标签序列,例如:

['NONE', 'NONE', 'salutation', 'salutation', 'NONE', 'NONE', 'NONE', 'verb', 'NONE', 'NONE', 'NONE', 'NONE', 'NONE', 'NONE', 'NONE', 'size', 'NONE', 'NONE']

在 Python 中实现此目的最简单的方法是什么?

最佳答案

您可以使用 BeautifulSoup 的递归来生成所有标签和内容的列表,然后可将其用于匹配标签:

from bs4 import BeautifulSoup as soup
import re
content = '<body><text>Hello world!</text><text>This is my code. And this is a number 42</text></body>'
def tokenize(d):
  yield f'<{d.name}>'
  for i in d.contents:
     if not isinstance(i, str):
       yield from tokenize(i)
     else:
       yield from i.split()
  yield f'</{d.name}>'

data = list(tokenize(soup(content, 'html.parser').body))

输出:

['<body>', '<text>', 'Hello', 'world!', '</text>', '<text>', 'This', 'is', 'my', 'code.', 'And', 'this', 'is', 'a', 'number', '42', '</text>', '</body>']

然后,匹配标签:

labels = [{'label':'salutation', 'start':12, 'end':25}, {'label':'verb', 'start':42, 'end':45}, {'label':'size', 'start':75, 'end':78}] 
tokens = [{**i, 'word':content[i['start']:i['end']-1].split()} for i in labels]
indices = {i:iter([[c, c+len(i)+1] for c in range(len(content)) if re.findall('^\W'+i, content[c-1:])]) for i in data}  
new_data = [[i, next(indices[i], None)] for i in data]
result = [(lambda x:'NONE' if not x else x[0])([c['label'] for c in tokens if b and c['start'] <= b[0] and b[-1] <= c['end']]) for a, b in new_data]

输出:

['NONE', 'NONE', 'salutation', 'salutation', 'NONE', 'NONE', 'NONE', 'verb', 'NONE', 'NONE', 'NONE', 'NONE', 'NONE', 'NONE', 'NONE', 'size', 'NONE', 'NONE']

关于python - 使用 Python 对 HTML 源代码进行标记和标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55796225/

相关文章:

python - 为一个键分配多个值?

python - 将带有列表的列的 pandas DF 写入文件,如何读回它?

python - Python for 语句的混淆行为

javascript - 如何在 meteor 中获取表单值?

C# 将字符串拆分为标记的更直观方法?

python - 检查 Unity 元目录中是否存在表

javascript - 本地托管的 Jquery.js 不工作,CDN 链接工作正常

javascript - 从文本框的列表项中选择部分文本

database - 用于分页的 Cassandra CQL token 函数

javascript - 当存在 constructor() 时调用异步函数