【问题标题】:How do I capture the first numeric element in a string in python? [duplicate]如何在python中捕获字符串中的第一个数字元素? [复制]
【发布时间】:2021-02-12 10:12:55
【问题描述】:

我有以下代码

import re
age = []

txt = ('9', "10y", "4y",'unknown')
for t in txt:
    if t.isdigit() is True:
        age.append(re.search(r'\d+',t).group(0))
    else:
        age.append('unknown')
print(age)

我得到: ['9', '未知', '未知', '未知']

所以我得到了 9,但我还需要在第二个位置得到 10,在第三个位置得到 4,最后一个是未知的。
谁能指出我正确的方向? 感谢您的帮助!

【问题讨论】:

  • 我不知道为什么它被选为重复我没有看到任何重复。a
  • 我认为标志是正确的。在提交问题之前,我确实经历了一个小时的堆栈溢出。我没有看到与我的问题相似的答案。该问题的答案类似于@Erfan pandas 解决方案。我一定错过了。谢谢大家的帮助

标签: python regex pandas string


【解决方案1】:

我们可以利用re.search在找不到任何数字时返回None这一事实:

txt = ('9', "10y", "4y",'unknown')
age = []
for t in txt:
    num = re.search('\d+', t)
    if num:
        age.append(num.group(0))
    else:
        age.append('unknown')
['9', '10', '4', 'unknown']

由于您标记了pandas,如果您有列,请使用str.extract

pd.Series(txt).str.extract('(\d+)')
0      9
1     10
2      4
3    NaN
dtype: object

【讨论】:

  • 谢谢!!!而已! Geesh...我应该在问题中提供更多背景信息......我一直在为宠物收容所做一些志愿者工作...数据框中的一列是 xY yM 多年和几个月。我只需要年龄来做一些分析,所以熊猫的想法可能是要走的路。再次感谢!
【解决方案2】:
import re
age = []

txt = ('9', "10y22", "4y", 'unknown')

for t in txt:
    res = re.findall('[0-9]+', t)
    if res:
        age.append(res[0])
    else:
        age.append("unknown")

【讨论】:

    【解决方案3】:
    import re
    
    
    age = []
    
    txt = ('9', "10y", "4y",'unknown')
    for t in txt:
        if len(t) > 1 and not t.isdigit():
            t = t.replace(t[-1], '')
        if t.isdigit() is True:
            age.append(re.search(r'\d+',t).group(0))
        else:
            age.append('unknown')
    print(age)
    

    看看这个。所以 len 函数检查字符串是否大于 1,然后如果字符串的最后一个字母不是数字,则字符串的最后一个字母被替换为空格。然后它遵循你算法的其余部分。您可以对其进行更多修改以满足您的要求,因为您没有指定那么多。

    【讨论】:

    • 谢谢,这真的很酷!
    猜你喜欢
    • 2018-08-05
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    相关资源
    最近更新 更多