3

假设有一个名为 likes_and_dislikes 的字符串,在视觉上被格式化为如下所示的表格。

如何解析字符串并返回包含好恶的元组列表。还必须从元组列表中删除顶部标题(喜欢,不喜欢)。

likes_and_dislikes="""

+------------------------------------+-----------------------------------+
| likes                              | dislikes                          |
+------------------------------------+-----------------------------------+
| Meritocracy                        | Favoritism, ass-kissing, politics |
+------------------------------------+-----------------------------------+
| Healthy debates and collaboration  | Ego-driven rhetoric, drama and FUD|
|                                    | to get one's way                  |
+------------------------------------+-----------------------------------+
| Autonomy given by confident leaders| Micro-management by insecure      |
| capable of attracting top-tier     | managers compensating for a weak, |
| talent                             | immature team                     |
+------------------------------------+-----------------------------------+  """
4

2 回答 2

3

这里的关键是彻底检查表格并了解您要提取的内容。

首先,像这样逐行解析字符串通常更容易,因此您需要根据表行进行拆分,然后根据该行解析列。我们这样做主要是因为喜欢和不喜欢跨越了界线。

1.获取每一行

我们不知道表格可能有多宽,所以我们使用正则表达式来分解我们的表格,如下所示:

pairs = re.split("\+-*\+-*\+\n?",likes_and_dislikes)[2:-1] #Drop the header and the tail

这为我们提供了一个与我们的多行行相对应的数组。最后的数组切片删除了标题和我们不想处理的任何尾随空格。但是,我们仍然存在将跨越单元格中多行的字符串拉在一起的问题。

2.找到喜欢和不喜欢

如果我们遍历这个行数组,我们知道每一行都有跨越未知行数组的喜欢和不喜欢。我们将这个喜欢和不喜欢的每个都初始化为一个数组,以使最后的连接更快。

for p in pairs:
  like,dislike = [],[]

3.处理每一行

对于我们的行,我们需要根据换行符对其进行拆分,然后根据管道 ( |) 进行拆分。

  for l in p.split('\n'):
    pair = l.split('|')

4.拉出每个喜欢和不喜欢

如果我们得到的一对有多个值,那么必须有一对喜欢或不喜欢我们来捕捉。所以将它附加到我们的likedislike数组中——而不是喜欢或不喜欢,因为它们保存了我们最终格式化的字符串。我们还应该strip对这些执行 a 以删除任何尾随或前导空格

    if len(pair) > 1:
      # Not a blank line
      like.append(pair[1].strip())
      dislike.append(pair[2].strip())

5. 创建最终文本

一旦我们完成了对行的处理,我们可以join the strings使用一个空格,最后可以将它们添加到我们的likesdislikes数组中。

  if len(like) > 0:
    likes.append(" ".join(like))
  if len(dislike) > 0:
    dislikes.append(" ".join(dislike))

6. 使用我们的新数据结构

现在我们可以使用这两个新列表以我们选择的任何方式进行处理,或者分别打印每个列表......

from pprint import pprint
print "Likes:"
pprint(likes,indent=4)
print "Dislikes:"
pprint(dislikes,indent=4)

... 或者zip()他们一起创建成对的好恶列表!

print "A set of paired likes and dislikes"
pprint(zip(likes,dislikes),indent=4)

完整代码:

likes_and_dislikes="""

+------------------------------------+-----------------------------------+
| likes                              | dislikes                          |
+------------------------------------+-----------------------------------+
| Meritocracy                        | Favoritism, ass-kissing, politics |
+------------------------------------+-----------------------------------+
| Healthy debates and collaboration  | Ego-driven rhetoric, drama and FUD|
|                                    | to get one's way                  |
+------------------------------------+-----------------------------------+
| Autonomy given by confident leaders| Micro-management by insecure      |
| capable of attracting top-tier     | managers compensating for a weak, |
| talent                             | immature team                     |
+------------------------------------+-----------------------------------+ """

import re
likes,dislikes = [],[]
pairs = re.split("\+-*\+-*\+\n?",likes_and_dislikes)[2:-1] #Drop the header and the tail
for p in pairs:
  like,dislike = [],[]
  for l in p.split('\n'):
    pair = l.split('|')
    if len(pair) > 1:
      # Not a blank line
      like.append(pair[1].strip())
      dislike.append(pair[2].strip())
  if len(like) > 0:
    likes.append(" ".join(like))
  if len(dislike) > 0:
    dislikes.append(" ".join(dislike))
from pprint import pprint
print "Likes:"
pprint(likes,indent=4)
print "Dislikes:"
pprint(dislikes,indent=4)
print "A set of paired likes and dislikes"
pprint(zip(likes,dislikes),indent=4)

这导致:

Likes:
[   'Meritocracy',
    'Healthy debates and collaboration ',
    'Autonomy given by confident leaders capable of attracting top-tier talent']
Dislikes:
[   'Favoritism, ass-kissing, politics',
    "Ego-driven rhetoric, drama and FUD to get one's way",
    'Micro-management by insecure managers compensating for a weak, immature team']
A set of paired likes and dislikes
[   ('Meritocracy', 'Favoritism, ass-kissing, politics'),
    (   'Healthy debates and collaboration ',
        "Ego-driven rhetoric, drama and FUD to get one's way"),
    (   'Autonomy given by confident leaders capable of attracting top-tier talent',
        'Micro-management by insecure managers compensating for a weak, immature team')]

您可以在 codepad 上看到完整的代码。

于 2013-09-23T23:46:37.220 回答
2

那是 ReST(重组文本,一种 pythonic 形式的标记)中使用的(其中一种)表格格式,并且有各种解析器在为它踢球。

这是一个,在旧的 python.org 网站上:http: //legacy.python.org/scripts/ht2html/docutils/parsers/rst/tableparser.py

于 2013-09-24T00:06:56.443 回答