有人能告诉我如何从Python输出中提取某些值吗?
我想使用索引或切片从以下输出中检索值'ocweeklyreports':
'config': '{"hiveView":"ocweeklycur.ocweeklyreports"}
这应该相对容易,但是,我在定义切片/索引配置时遇到了问题
下面的代码将成功地返回'ocweeklyreports'
myslice = config['hiveView'][12:30]
但是,我需要修改索引或切片,以便我将获得'ocweeklycur'之后的任何值
我不确定你正在处理什么输出以及你想要它有多健壮,但如果它只是一个字符串,你可以做类似的事情(为了一个快速和肮脏的解决方案)。
input = "Your input"
indexStart = input.index('.') + 1 # Get the index of the input at the . which is where you would like to start collecting it
finalResponse = input[indexStart:-2])
print(finalResponse) # Prints ocweeklyreports
不是最优雅的解决方案,但希望它能有所帮助,或者至少提供一个起点。另一个更健壮的解决方案是使用regex,但我目前对regex不太熟练。
您几乎可以使用正则表达式。看看是否有帮助:
import re
def search_word(di):
st = di["config"]["hiveView"]
p = re.compile(r'^ocweeklycur.(?P<word>w+)')
m = p.search(st)
return m.group('word')
if __name__=="__main__":
d = {'config': {"hiveView":"ocweeklycur.ocweeklyreports"}}
print(search_word(d))
下面这些对我来说效果最好:
# Extract the value of the "hiveView" key
hive_view = config['hiveView']
# Split the string on the '.' character
parts = hive_view.split('.')
# The value you want is the second part of the split string
desired_value = parts[1]
print(desired_value) # Output: "ocweeklyreports"