【发布时间】: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