[英]how to print after the keyword from python?
i have following string in python我在 python 中有以下字符串
b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a","persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],"name":"waqas"}'
I want to print the all alphabet next to keyword "name" such that my output should be我想打印关键字“名称”旁边的所有字母,这样我的 output 应该是
waqas
Note the waqas can be changed to any number so i want print any name next to keyword name using string operation or regex?请注意,waqas 可以更改为任何数字,所以我想使用字符串操作或正则表达式在关键字名称旁边打印任何名称?
First you need to decode the string since it is binary b
.首先,您需要解码字符串,因为它是二进制
b
。 Then use literal eval
to make the dictionary, then you can access by key
然后使用
literal eval
制作字典,然后就可以key
访问了
>>> s = b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a","persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],"name":"waqas"}'
>>> import ast
>>> ast.literal_eval(s.decode())['name']
'waqas'
It is likely you should be reading your data into your program in a different manner than you are doing now.您可能应该以与现在不同的方式将数据读入程序。
If I assume your data is inside a JSON file, try something like the following, using the built-in json
module:如果我假设您的数据在 JSON 文件中,请使用内置的
json
模块尝试以下操作:
import json
with open(filename) as fp:
data = json.load(fp)
print(data['name'])
You can convert the string into a dictionary with json.loads()
您可以使用
json.loads()
将字符串转换为字典
import json
mystring = b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a","persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],"name":"waqas"}'
mydict = json.loads(mystring)
print(mydict["name"])
# output 'waqas'
if you want a more algorithmic way to extract the value of name
:如果您想要一种更算法的方法来提取
name
的值:
s = b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a",\
"persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],\
"name":"waqas"}'
s = s.decode("utf-8")
key = '"name":"'
start = s.find(key) + len(key)
stop = s.find('"', start + 1)
extracted_string = s[start : stop]
print(extracted_string)
output output
waqas
First you need to convert the string into a proper JSON
Format by removing b from the string using substring in python suppose you have a variable x
:首先,您需要使用 python 中的 substring 从字符串中删除 b ,将字符串转换为正确的
JSON
格式,假设您有一个变量x
:
import json
x = x[1:];
dict = json.loads(x) //convert JSON string into dictionary
print(dict["name"])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.