python - Python中的字符串到JSON
问题描述
我有一个示例字符串,我需要将字符串转换为 JSON 格式。我尝试了多种方法但无法实现,如果有人帮助我构建它,那听起来真的很棒。示例字符串位置不断变化,我们需要根据存在的 JSON 键选择数据。
示例字符串:
sample ="The following are the graphical (non-control) characters defined by
ISO 8859-1 (1987). DESCRIPTION : in words aren't all that helpful,
but they're the best we can do in text. A graphics file illustrating
the character set should be available from the same archive as this
file.RESULT :success INTERPRETATION : ISO 8859-1 (1987).CREATED_BY:Questy.CREATED_ON:29/07/1963"
所需的 JSON 输出
{
"DESCRIPTION":" in words aren't all that helpful but they're the best we can do in text. A graphics file illustrating the character set should be available from the same archive as thisfile",
"RESULT":"success",
"INTERPRETATION":" ISO 8859-1 (1987)",
"CREATED_BY":"Questy",
"CREATED_ON":"29/07/1963"
}
解决方案
我不想使用正则表达式,只是字符串方法
sample = ("The following are the graphical (non-control) characters defined "
"by ISO 8859-1 (1987). DESCRIPTION : in words aren't all that "
"helpful, but they're the best we can do in text. A graphics file "
"illustrating the character set should be available from the same "
"archive as this file.RESULT :success INTERPRETATION : ISO 8859-1 "
"(1987).CREATED_BY: Questy.CREATED_ON:29/07/1963")
sample = sample.replace('.', '. ').replace('. ', '. ')
lst = list(map(str.strip, sample.split(':')))
result = {}
for i in range(len(lst)-1):
if i < len(lst)-2:
result[lst[i].split()[-1]] = ' '.join(lst[i+1].split()[:-1]).strip('.')
else:
result[lst[i].split()[-1]] = lst[i+1].strip('.')
>>> result
{'CREATED_BY': 'Questy',
'CREATED_ON': '29/07/1963',
'DESCRIPTION': "in words aren't all that helpful, but they're the best we can "
'do in text. A graphics file illustrating the character set '
'should be available from the same archive as this file',
'INTERPRETATION': 'ISO 8859-1 (1987)',
'RESULT': 'success'}
推荐阅读
- google-apps-script - Google 脚本检查包含公式的单元格中的邮件地址
- angular - 双击 Angular 时自动拖放
- django - Django中显示发件人电子邮件的错误
- python - numpyArr[:,:,:,c] 和 numpyArr[...,c] 有什么区别?
- c++ - 如何将 Qt 与 Visual Studio C++ 应用程序项目联系起来?
- android - 为什么searchview只输出listview上的第一项?
- javafx - Javafx - 为条形图设置悬停
- javascript - 我无法在 javascript 中访问 radgrid 列..我如何访问这个..?
- javascript - 当我们使用 css 下拉菜单作为共享组件时如何设置和获取表单值
- python - numpy sum min max 函数在聚合或应用于列表或数组时的不同行为