获取一个包含特定变量的所有值的数组

时间:2018-04-04 08:02:06

标签: python python-3.x python-2.7

我想知道如何获取特定信息的所有价值。在这种情况下,我想获取消息的所有“名称”并将其转换为数组。消息示例:

"xxxxxxxxxx name:yyyy; xxxxxxxxxxxxxxxxxxx name:yyyyy;"

代码(我只获得了第一个'名称'):

 for i in range(0,len(message)):  
     start = message.find('name') + 4
     end = message.find(';', start)
     a=message[start:end]
     split=a.split(';')
  print(split)

4 个答案:

答案 0 :(得分:5)

使用正则表达式:

import re
s = "xxxxxxxxxx name:yyyy; xxxxxxxxxxxxxxxxxxx name:yyyyy;"
print(re.findall(r"name:[a-zA-Z]+", s))

<强>输出:

['name:yyyy', 'name:yyyyy']

答案 1 :(得分:2)

如果您想使用str.find,则应为start提供一个起始位置,就像您对end所做的那样,例如第一次迭代中的上一个end0。然后,继续,直到start-1,即找不到。

end = 0
while True:
    start = message.find('name', end)
    if start == -1:
        break
    end = message.find(';', start)
    a = message[start + 5 : end]
    print(start, end, repr(a))

或者您可以在空白处split发送消息并使用条件列表理解:

>>> [s[5:-1] for s in message.split() if s.startswith("name")]
['yyyy', 'yyyyy']

但实际上,我建议使用正则表达式,如other answer

所示

答案 2 :(得分:1)

您的逻辑几乎可以运作,您可以将其更改为:

message = "xxxxxxxxxx name:yyyy; xxxxxxxxxxxxxxxxxxx name:zzzzzz;"

start = message.find('name')      # find first start
stop = message.find(';', start)   # find first stop after first start
names = []                        # all your found values get appended into this

while -1 < start < stop: # ensure start is found and stop is after it
    names.append(message[start+5:stop]) # add 5 start-pos to skip 'name:' and slice value
                                        # from message and put into names

    start = message.find('name',stop)   # find next start after this match
    if start == -1:                     # if none found, you are done
        stop = -1
    else:
        stop = message.find(';', start) # else find the end for this start

if start != -1:     # if your last ; is missing, the while above will find 
                    # start but no stop, in that case add all from last start pos to end
    names.append(message[start:])

print ( names)

输出:

['yyyy', 'zzzzzz']

答案 3 :(得分:1)

def formatFunction(x):
    index_of_name = x.index('name')
    if index_of_name >= 0:
        return x[index_of_name:]
    else:
        return None

message_list = message.split(';')
message_list = message_list.map(formatFunction)
formated_list = [x for x in message_list if x]
print(formated_list)