首页 > 解决方案 > 从 numpy 数组中的大字符串中获取子字符串

问题描述

我有一个 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 个样本,但在此先感谢您的帮助

标签: pythonarraysstringfor-loop

解决方案


您可以尝试通过迭代字符串并使用 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

推荐阅读