【问题标题】:Getting substring from a large string in a numpy array从 numpy 数组中的大字符串中获取子字符串
【发布时间】:2020-12-03 07:34:06
【问题描述】:

我有一个 np.array 包含一组字符串(每个字符串的长度不同),如下例所示:

title=['the first step in 2017', 'Here is my 2016 report', '2016 new considerations' ....] 

我想从我编写的这段代码的数组中的每个元素中提取年份:

list_yea=[]
    for i, tit in enumerate(title) : 
        if '20' in tit:
               print(year)# ??? I could not find a best solution 
               list_yea.append(year)

我假设所有年份都在 [2000-2020] 范围内我的问题是如何从该字符串中只返回年份

我已经尝试过这段代码,但它给了我错误的结果:

years=[]
c=1 # tocheck the number of string does not contain the year 
for i, tit in enumerate(title) :
    if '20' in tit or '199' in tit : # for both 199x and 20xx years
        spl=tit.split(' ')
        for j , check in enumerate(spl):
            if '20' in check:
                years.append(check)
    if '20' not in tit and '199' not in tit :
        c=c+1
        years.append(0)

len(years) ==> 16732 虽然我的总数据集是 16914 个样本 提前感谢您的任何帮助

【问题讨论】:

    标签: python arrays string for-loop


    【解决方案1】:

    您可以尝试遍历字符串并使用 try 和 except 检查它是否为整数,然后检查它是否以 20 开头(从 2000 年开始的年份)并且子字符串的长度为 4(如果有其他数字)

    list_yea=[]
    for i, tit in enumerate(title) : 
        for j in tit.split():
            try:        
                year = int(j)
                if len(j)==4 and '20' in j:
                    list_yea.append(j)
            except:
                   pass
    

    【讨论】:

    • @baddy 你能分享一下输出吗
    • @baddy 我忘了拆分字符串。现在这段代码给出了数组中字符串中存在的年份
    【解决方案2】:

    满足要求的最简单解决方案:

    import re
    
    title=['the first step in 2017', 'Here is my 2016 report', '2016 new considerations']
    
    for t in title:
        print(re.findall(r"[0-9]+", t)[0])
    

    如果您愿意,您可以进一步专门化正则表达式。

    【讨论】:

    • 如果字符串不包含年份,则索引超出范围
    • 因此,只需在访问第 0 个元素之前检查长度即可。
    猜你喜欢
    • 2011-11-30
    • 2011-10-06
    • 2018-09-27
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2017-08-05
    • 2015-08-21
    相关资源
    最近更新 更多