【问题标题】:How to extract only one string from regex in Python?如何从 Python 中的正则表达式中仅提取一个字符串?
【发布时间】:2017-12-05 11:01:53
【问题描述】:

我一直在尝试使用 Python 为自己构建一个简单的客户经理类型的应用程序,该应用程序将从我的手机中读取 SMS 并根据一些正则表达式模式提取信息。

我编写了一个复杂的正则表达式模式并在https://pythex.org/ 上进行了测试。 示例:

Text: 1.00 is debited from ******1234  for food

Pattern: (account|a\/c|ac|from|acct|savings|credit in|ac\/|sb\-|acc|a\/c)(\s|\.|\-)*(no|number)*(\.|\s|:)*\s*(ending)*\s*(((n{1,}|x{1,}|[0-9]+|\*{1,}))+)\-*((n{1,}|x{1,}|[0-9]+|\*{1,}|\s))*\-*([0-9]*)

Result: from ******1234

但是,当我尝试在 Python 中使用 str.extract() 方法执行相同操作时,我得到的不是单个结果,而是每个组都有一个列的数据框。

Python 代码如下所示:

all_sms=pd.read_csv("all_sms.csv")

pattern = '(account|a\/c|ac|from|acct|savings|credit in|ac\/|sb\-|acc|a\/c)(\s|\.|\-)*(no|number)*(\.|\s|:)*\s*(ending)*\s*(((n{1,}|x{1,}|[0-9]+|\*{1,}))+)\-*((n{1,}|x{1,}|[0-9]+|\*{1,}|\s))*\-*([0-9]*)'

test = all_sms.extract(pattern, expand = False)

上述消息的python代码输出:

0           from
1               
2            NaN
3            NaN
4            NaN
5     ******1234
6           1234
7           1234
8               
9               
10              

我对 Python 非常陌生,并试图通过实践经验来学习,如果有人能指出我在这方面哪里出了问题,那将非常有帮助?

【问题讨论】:

  • 在每个未转义的 ( 之后放置 ?:。删除多余的捕获组。
  • 如果这是关于特定语言的,请考虑使用语言标签

标签: python regex string text-extraction


【解决方案1】:

在深入了解您的正则表达式模式之前,您应该了解您使用的原因 熊猫。 Pandas 适用于数据分析(因此适合您的问题) 但在这里似乎有点过头了。

如果您是初学者,我建议您坚持使用纯 python,而不是因为 pandas 很复杂,但是因为了解 python 标准库会帮助你 从长远来看。如果您现在跳过基础知识,从长远来看这可能会伤害您。

考虑到您将使用 python3(没有 pandas),我将继续 关注:

# Needed imports from standard library.
import csv
import re

# Declare the constants of my tiny program.
PATTERN = '(account|a\/c|ac|from|acct|savings|credit in|ac\/|sb\-|acc|a\/c)(\s|\.|\-)*(no|number)*(\.|\s|:)*\s*(ending)*\s*(((n{1,}|x{1,}|[0-9]+|\*{1,}))+)\-*((n{1,}|x{1,}|[0-9]+|\*{1,}|\s))*\-*([0-9]*)'
COMPILED_REGEX = re.compile(PATTERN)

# This list will store the matched regex.
found_regexes = list()

# Do the necessary loading to enable searching for the regex.
with open('mysmspath.csv', newline='') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=' ', quotechar='"')
    # Iterate over rows in your csv file.
    for row in csv_reader:
        match = COMPILED_REGEX.search(row)
        if match:
            found_regexes.append(row)

print(found_regexes)

这不一定能解决你的复制粘贴问题,但这可能会给你一个 想出一种更简单的方法来解决您的问题。

【讨论】:

  • 感谢您的详细回答和解释。现在将尝试坚持基础知识:)
猜你喜欢
  • 1970-01-01
  • 2015-08-19
  • 2016-04-10
  • 1970-01-01
  • 2014-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多