python - 从 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
推荐阅读
- ios - UITableviewCell 中的两个 UILabel 以编程方式并排在 swift 中
- php - 如何使用 HTML CSS 在 pdf 中创建颜色框
- c# - ASP.NET Core 1.0 中的后台任务
- python - 使用 BeautifulSoup 获取 tr 标签时出现问题
- html - 如何在 .htaccess 上限制 RewriteEngine
- c++ - 无法更新此内容,因此这将以列格式显示给定目录的目录列表
- mongodb - 如何使用 mongo-java-driver 使用 MongoDB 实现文档级锁定功能?
- excel - 在链中使用多个样式
- java - Kotlin 中的 Java 默认方法
- autodesk-forge - 覆盖 Forge Viewer 上元素的不透明度