python - Python如何从字符串中提取用括号括起来的数据
问题描述
我正在尝试找到一种智能且快速的解决方案来从字符串中提取一些数据。
基本上我想在'(...)'中获取所有文本
例子:
ex_string= "My Cell Phone number is (21) 99715-5555"
return = 21
ex_string2 = "Apple (AAPL) have a great quarterly, but Microsoft (MSFT) have a better one"
return = ['AAPL', 'MSFT']
ex_string3 = "Hello World"
return = None
诀窍是一些字符串只有一个项目,另一个会有更多,另一个没有。
我知道我可以 .split('(') 然后开始获取项目,但试图为这种情况找到更好的解决方案,因为我会解析大量的字符串。
解决方案
您可以使用正则表达式。
这是我的写法:
import re
def find_enclosed(s):
# find all matches
matches = re.findall(r"\((.*?)\)", s)
# if there are no matches return None
if len(matches) == 0:
return None
# if it is a valid number change its type to a number
for i in range(len(matches)):
try:
matches[i] = int(matches[i])
except:
pass
# if there is only one match return it without a list
if len(matches) == 1:
return matches[0]
return matches
这就是你将如何使用它:
ex_string= "My Cell Phone number is (21) 99715-5555"
ex_string2 = "Apple (AAPL) have a great quarterly, but Microsoft (MSFT) have a better one"
matches1 = find_enclosed(ex_string1)
matches2 = find_enclosed(ex_string2)
print(matches1)
print(matches2)
推荐阅读
- javascript - Python Jinja2从后端分配javascript var
- php - 存储中的模拟文件以在 Laravel 中下载
- javascript - jsperf:未捕获的 HierarchyRequestError:无法在“节点”上执行“appendChild”:此节点类型不支持此方法
- html - 扩展 base.html 后,我的孩子 html 的东西没有显示
- java - 不能在子进程中将 HashMap 用于 TIMESTAMP
- docker - 将独立客户端构建输出同步到一个 docker Web 服务器构建
- vue.js - 为什么在将数据分配给变量时计算会更改数据?
- c# - redis设置相同的key,性能问题?
- google-photos-api - 有没有办法通过 Google Photos API 使用高质量模式?
- android - 在主要活动的背景上显示的启动画面