如何解决从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个样本
预先感谢您的帮助
解决方法
您可以尝试遍历字符串,并使用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
,
满足要求的最简单的解决方案:
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])
如果愿意,可以进一步专门化正则表达式。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。