gpt4 book ai didi

Python如何从字符串中提取括号括起来的数据

转载 作者:行者123 更新时间:2023-12-04 07:16:28 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Regular expression to return text between parenthesis

(7 个回答)


18 天前关闭。




我正在尝试找到一种智能且快速的解决方案来从字符串中提取一些数据。
基本上我想在'(...)'中获取所有文本
例子:

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('(') 然后开始获取项目,但试图为这种情况找到更好的解决方案,因为我将解析大量字符串。

最佳答案

您可以使用 regular expressions .
这是我将如何编写它:

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)

关于Python如何从字符串中提取括号括起来的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68728335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com