如何从句子中选择括号内的单词?

2024-04-19 13:48:09 发布

您现在位置:Python中文网/ 问答频道 /正文

如何选择 [Andrey][21]来自info?你知道吗

info = "my name is [Andrey] and I am [21] years old"
result = ["[Andrey]", "[21]"];

Tags: andnameinfoismyresultamold
2条回答

您可以选择regex方法。你知道吗

或者简单地将列表理解用于您的用例:

>>> print([ lst[index] for index in [3,7] ])
['[Andrey]', '[21]']

但另一种方法是,首先将字符串转换为list,然后在itemgetter的帮助下选择by index方法:

>>> info = "my name is [Andrey] and I am [21] years old"
>>> lst = info.split()
>>> lst
['my', 'name', 'is', '[Andrey]', 'and', 'I', 'am', '[21]', 'years', 'old']
>>> from operator import itemgetter
>>> print(itemgetter(3,7)(lst))
('[Andrey]', '[21]')

我相信其他方法会更好。但我试过了,它成功了。
如果要在不知道位置的情况下提取[]中的字符,可以使用以下方法:
在字符串中运行for循环
如果你找到了角色[
在字符串中追加所有下一个字符,直到找到]
您可以将这些字符串添加到一个列表中,以获取结果。这是密码。

info = "my name is [Andrey] and I am [21] years old"
s=[]    #list to collect searched result
s1=""   #elements of s
for i in range(len(info)):
    if info[i]=="[":
        while info[i+1] != "]":
            s1 += info[i+1]
            i=i+1
        s.append(s1)
        s1=""
        #make s1 empty to search for another string inside []
print s

输出为:

['Andrey', '21']

相关问题 更多 >