首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从字符串Python中提取值

从字符串Python中提取值
EN

Stack Overflow用户
提问于 2019-05-10 01:53:25
回答 4查看 4.8K关注 0票数 0

处理机器人应用程序,所以我需要从消息字符串中提取值,并将其传递给一个变量。消息字符串可以采用不同的方式,例如:

代码语言:javascript
复制
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.

可以检查循环中的每个单词并提取字符串,但它会变得相当长。如果有更简单的方法,请告诉我

喜欢

代码语言:javascript
复制
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
EN

回答 4

Stack Overflow用户

发布于 2019-05-10 02:03:41

如果你只是想测试age,你可以搜索这个字符串。如果除了检查年龄之外,你还想用它做其他事情,你可以把它分成一个字典。

代码语言:javascript
复制
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'
票数 1
EN

Stack Overflow用户

发布于 2019-05-10 02:10:30

您可以做的一件事是使用正则表达式并提取单独的部分。

例如,假设您的消息是message = 'name="Raj",lastname="Paul",gender="male", age=23',您可以将正则表达式设置为(?P<var>.*?)=(?P<out>.*?),

以下是我会做的事情:

代码语言:javascript
复制
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,你可以去掉双引号。

要获取所有字段,您可以执行以下操作:

代码语言:javascript
复制
for field in extracted:
    print(field, extracted[field])

# Prints
name "Raj"
lastname "Paul"
gender "male"
age 23
票数 1
EN

Stack Overflow用户

发布于 2019-05-10 02:29:30

代码语言:javascript
复制
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)

此代码将以下输出作为字典返回。您可以遍历每条消息,它会将正确的属性与正确的键放在一起。

代码语言:javascript
复制
{'name': 'Raj', 'lastname': 'Paul', 'gender': 'male', 'age': '23'}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56065023

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档