处理机器人应用程序,所以我需要从消息字符串中提取值,并将其传递给一个变量。消息字符串可以采用不同的方式,例如:
message = 'name="Raj",lastname="Paul",gender="male", age=23'
message = 'name="Raj",lastname="Paul",age=23'
message = 'name="Raj",lastname="Paul",gender="male"'
用户提供的数据可以包含所有值,或者有时会缺少年龄或性别字段。
我被卡住的地方是,I am not sure how to check if age is present in the message text. If it is then extract value corresponding to age. If age is not in message, ignore age.
可以检查循环中的每个单词并提取字符串,但它会变得相当长。如果有更简单的方法,请告诉我
喜欢
if Age is present in message then get the value of age,
if lastname is present in message then get the value of lastname
if gender is present in message then get the value of gender
if name is present in message then get the value of name
发布于 2019-05-10 02:03:41
如果你只是想测试age
,你可以搜索这个字符串。如果除了检查年龄之外,你还想用它做其他事情,你可以把它分成一个字典。
message = 'name="Raj",lastname="Paul",gender="male", age=23'
pairs = [pair.replace('"', '').strip() for pair in message.split(',')]
d = dict([p.split('=') for p in pairs])
'age' in d # True
d['name'] # 'Raj'
发布于 2019-05-10 02:10:30
您可以做的一件事是使用正则表达式并提取单独的部分。
例如,假设您的消息是message = 'name="Raj",lastname="Paul",gender="male", age=23'
,您可以将正则表达式设置为(?P<var>.*?)=(?P<out>.*?),
以下是我会做的事情:
import re
message = 'name="Raj",lastname="Paul",gender="male", age=23'
message += ',' # Add a comma for the regex
findall = re.findall(r'(?P<var>.*?)=(?P<out>.*?),', message) # Note the additional comma
extracted = {k.strip(): v.strip() for k,v in findall}
if 'age' in extracted:
print(extracted['age']) # prints 23
然后提取出如下所示的地图:{'name': '"Raj"', 'lastname': '"Paul"', 'gender': '"male"', 'age': '23'}
。如果你真的想把age转换成int,你可以去掉双引号。
要获取所有字段,您可以执行以下操作:
for field in extracted:
print(field, extracted[field])
# Prints
name "Raj"
lastname "Paul"
gender "male"
age 23
发布于 2019-05-10 02:29:30
message = 'name="Raj",lastname="Paul",gender="male", age=23'
new_msg = message.replace('"', '').replace(' ', '').split(',') # 2nd replace to delete the extra space before age
msg_dict = dict([x.split('=') for x in new_msg])
print(msg_dict)
此代码将以下输出作为字典返回。您可以遍历每条消息,它会将正确的属性与正确的键放在一起。
{'name': 'Raj', 'lastname': 'Paul', 'gender': 'male', 'age': '23'}
https://stackoverflow.com/questions/56065023
复制相似问题