繁体   English   中英

在 Python 中使用正则表达式从文本中提取列表

[英]Extracting a List from Text using Regular Expression in Python

我希望从以下字符串中提取元组列表:

text='''Consumer Price Index:
        +0.2% in Sep 2020

        Unemployment Rate:
        +7.9% in Sep 2020

        Producer Price Index:
        +0.4% in Sep 2020

        Employment Cost Index:
        +0.5% in 2nd Qtr of 2020

        Productivity:
        +10.1% in 2nd Qtr of 2020

        Import Price Index:
        +0.3% in Sep 2020

        Export Price Index:
        +0.6% in Sep 2020'''

我在这个过程中使用了“import re”。

输出应该类似于:[('Consumer Price Index', '+0.2%', 'Sep 2020'), ...]

我想使用产生上述输出的 re.findall 函数,到目前为止我有这个:

re.findall(r"(:\Z)\s+(%\Z+)(\Ain )", text)

我在哪里识别':'之前的字符,然后是'%'之前的字符,然后是'in'之后的字符。

我真的只是不知道如何继续。 任何帮助,将不胜感激。 谢谢!

您可以使用

re.findall(r'(\S.*):\n\s*(\+?\d[\d.]*%)\s+in\s+(.*)', text)
# => [('Consumer Price Index', '+0.2%', 'Sep 2020'), ('Unemployment Rate', '+7.9%', 'Sep 2020'), ('Producer Price Index', '+0.4%', 'Sep 2020'), ('Employment Cost Index', '+0.5%', '2nd Qtr of 2020'), ('Productivity', '+10.1%', '2nd Qtr of 2020'), ('Import Price Index', '+0.3%', 'Sep 2020'), ('Export Price Index', '+0.6%', 'Sep 2020')]

请参阅正则表达式演示Python 演示

细节

  • (\\S.*) - 第 1 组:非空白字符后跟尽可能多的除换行符以外的零个或多个字符
  • : - 一个冒号
  • \\n - 换行
  • \\s* - 0 个或多个空格
  • (\\+?\\d[\\d.]*%) - 第 2 组:可选+ 、一个数字、零个或多个数字/点和一个%
  • \\s+in\\s+ - in包围1+空格
  • (.*) - 第 3 组:尽可能多的除换行符以外的零个或多个字符

正则表达式不是解决这个问题的好方法。 它变得难以阅读和维护得非常快。 使用 python 字符串函数可以更简洁:

list_of_lines = [
    line.strip()                 # remove trailing and leading whitespace
    for line in text.split("\n") # split up the text into lines
    if line                      # filter out the empty lines
]

list_of_lines现在是:

['Consumer Price Index:', '+0.2% in Sep 2020', 'Unemployment Rate:', '+7.9% in Sep 2020', 'Producer Price Index:', '+0.4% in Sep 2020', 'Employment Cost Index:', '+0.5% in 2nd Qtr of 2020', 'Productivity:', '+10.1% in 2nd Qtr of 2020', 'Import Price Index:', '+0.3% in Sep 2020', 'Export Price Index:', '+0.6% in Sep 2020']

现在我们要做的就是从这个列表的元素对构建元组。

def pairwise(iterable):
    "s -> (s0, s1), (s2, s3), (s4, s5), ..."
    a = iter(iterable)
    return zip(a, a)

(从这里

现在我们可以得到我们想要的输出:

print(pairwise(list_of_lines))
[('Consumer Price Index:', '+0.2% in Sep 2020'), ('Unemployment Rate:', '+7.9% in Sep 2020'), ('Producer Price Index:', '+0.4% in Sep 2020'), ('Employment Cost Index:', '+0.5% in 2nd Qtr of 2020'), ('Productivity:', '+10.1% in 2nd Qtr of 2020'), ('Import Price Index:', '+0.3% in Sep 2020'), ('Export Price Index:', '+0.6% in Sep 2020')]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM