【发布时间】:2017-07-20 15:36:20
【问题描述】:
我正在尝试匹配一个逗号分隔的 key=value 列表,坦率地说,该值可以包含很多东西。
我使用的模式正是来自这个related question:
split_up_pattern = re.compile(r'([^=]+)=([^=]+)(?:,|$)', re.X|re.M)
但是当值包含 html 时会导致问题。
这是一个示例脚本:
import re
text = '''package_contents=<p>The basic Super 1050 machine includes the following:</p>
<p> </p>
<table style="" height: 567px;"" border=""1"">
<tbody>
<tr>
<td style=""width: 200px;"">
<ul>
<li>uper 1150 machine</li>
</ul>
</td>
<td> With dies fitted.
<ul>
<li>The Super 1050</li>
</ul>
</td>
</tr>
</tbody>
<table>,second_attribute=something else'''
split_up_pattern = re.compile(r'([\w_^=]+)=([^=]+)(?:,|$)', re.X|re.M)
matches = split_up_pattern.findall(text)
import ipdb; ipdb.set_trace()
print(matches)
输出:
ipdb> matches[0]
('package_contents', '<p>The basic Super 1050 machine includes the following:</p>\n\n<p> </p>\n')
ipdb> matches[1]
('border', '""1"">\n\n<tbody>\n\n<tr>\n')
ipdb> matches[2]
('style', '""width: 200px;"">\n\n<ul>\n\n<li>uper 1150 machine</li>\n\n</ul>\n\n</td>\n\n<td> With dies fitted.\n\n<ul>\n\n<li>The Super 1050</li>\n\n</ul>\n\n</td>\n\n</tr>\n</tbody>\n<table>')
ipdb> matches[3]
('second_attribute', 'something else')
我想要的输出是:
matches[0]:
('package_contents', '<p>The basic Super 1050 machine includes the following:</p><p> </p><table style="" height: 567px;"" border=""1""><tbody><tr><td style=""width: 200px;""><ul><li>uper 1150 machine</li></ul></td><td> With dies fitted.<ul><li>The Super 1050</li></ul></td></tr>
</tbody><table>',)
matches[1]:
('second_attribute', 'something else')
【问题讨论】:
-
这是一个棘手的问题,您最初是如何获得这些数据的?您有什么方法可以在源头上对其进行标记?如果不能保证分隔符不会出现在值中,那么所有通过正则表达式(以及实际上大多数其他方法)进行解析的赌注都将被取消。您需要找到一个永远不会出现在值中的分隔符。
-
您正在为多行正则表达式使用
re.M标志。我怀疑这是一个错误。 -
如果逗号从未出现在 HTML 中的任何位置,则将搜索更改为
split_up_pattern = re.compile(r'([^=]+)=([^,]+)(?:,|$)')应该可以。 -
@Phylogenesis 不幸的是,逗号确实出现了。
-
@ffledgling 我正在从电子商务网站导出。所以输出是
csv格式。然而,一列合并了所有additional_attributes,如上所示