【问题标题】:Extract salaries from a list of strings从字符串列表中提取薪水
【发布时间】:2019-08-26 01:17:13
【问题描述】:

我正在尝试从字符串列表中提取薪水。 我正在使用正则表达式 findall() 函数,但它返回了许多空字符串以及薪水,这导致我稍后在代码中出现问题。


sal= '41 000€ à 63 000€ / an' #this is a sample string for which i have errors

regex = ' ?([0-9]* ?[0-9]?[0-9]?[0-9]?)'#this is my regex

re.findall(regex,sal)[0]
#returns '41 000' as expected but:
re.findall(regex,sal)[1]
#returns: '' 
#Desired result : '63 000'

#the whole list of matches is like this:
['41 000',
 '',
 '',
 '',
 '',
 '',
 '',
 '63 000',
 '',
 '',
 '',
 '',
 '',
 '',
 '',
 '',
 '']
# I would prefer ['41 000','63 000']

有人可以帮忙吗? 谢谢

【问题讨论】:

  • 您的模式可以匹配一个空字符串,所以实际上是您要求的。您要匹配的模式是什么?以空格作为数字分组符号的数字?试试r'(?<!\d)\d{1,3}(?: \d{3})*(?!\d)'
  • 你可以试试这个模式 (\d+(?: \d{1,3})?)€ 和 findall 只返回工资。 Demo
  • np.concatenate(re.findall(regex,sal)[0],re.findall(regex,sal)[1])
  • 是否只提取 后面的数字?然后尝试r'(?<!\d)(\d{1,3}(?:[ \xA0]\d{3})*)\s*€',或r'(?<!\d)(\d+|\d{1,3}(?:[ \xA0]\d{3})*)\s*€'。见regex101.com/r/rwbpTx/1
  • 谢谢大家!

标签: python regex string list findall


【解决方案1】:

使用re.findall 将在您在模式中使用它们时为您提供捕获组,并且您使用的组几乎所有内容都是可选的,从而在结果中为您提供空字符串。

在您的模式中,您使用 [0-9]* 将匹配 0+ 次数字。如果前导数字没有限制,您可以使用[0-9]+ 代替,而不是使其成为可选。

您可以将此模式与捕获组一起使用:

(?<!\S)([0-9]+(?: [0-9]{1,3})?)€(?!\S)

Regex demo | Python demo

说明

  • (?&lt;!\S)断言左边不是非空白字符
  • (抓拍群
    • [0-9]+(?: [0-9]{1,3})? 匹配 1+ 位数字,后跟与空格和 1-3 位数字匹配的可选部分
  • )关闭捕获组
  • 字面上匹配
  • (?!\S)断言右边不是非空白字符

您的代码可能如下所示:

import re
sal= '41 000€ à 63 000€ / an' #this is a sample string for which i have errors
regex = '(?<!\S)([0-9]+(?: [0-9]{1,3})?)€(?!\S)'
print(re.findall(regex,sal))  # ['41 000', '63 000']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 2021-11-07
    • 2018-12-13
    • 1970-01-01
    • 2019-04-30
    相关资源
    最近更新 更多