python - 如何在Python中将一行文本文件向上移动一行?
问题描述
我有一个包含一些参数及其值的文本文件。在 python 中解析它之后,创建了一个字典。文本文件类似于:
Object1
House: Blue
Car: Red
Green
Garden: Big
Object2
House: Beatiful
Car: Nice
Garden: Small
创建字典后,我还创建了一些块,然后帮助我解析 json 文件中的所有内容。问题是“绿色”没有被检测为汽车的值,而是作为一个新对象。因此,我想做的是将“绿色”字符串移动一行并拥有一个像这样的文本文件。
Object1
House: Blue
Car: Red Green
Garden: Big
Object2
House: Beatiful
Car: Nice
Garden: Small
我怎样才能在 Python 中做到这一点?我正在考虑使用正则表达式函数来查找绿色,但我仍然不知道如何将它排成一行。
一段代码:
to_json = {}
answer = {}
block_cnt = 1
header = re.compile('[a-zA-Z0-9]')
inner = re.compile("[\t]")
empty = re.compile("[\n]",)
with open(output, 'r') as document:
for line in document:
#print line
if empty.match(line[0]):
continue
elif header.match(line[0]):
if answer:
to_json[block_cnt] = answer
#print answer
block_cnt += 1
answer = {}
elif inner.match(line[0]):
_key, value = line.split(": ")
tab, key = _key.split("\t")
answer[key] = value.strip("\n")
解决方案
问题:我正在考虑使用正则表达式函数来查找绿色,但我仍然不知道如何将它排成一行。
你的错误之一是.match(line[0])
。
您匹配 中的第一个字符line
。这不是你想要的,改为.match(line)
这将产生以下输出:
header:Object1 header:Green empty: header:Object2 {}
你的header = re.compile('[a-zA-Z0-9]')
比赛也是Green
.
您如何区分“绿色”和标题?
你的inner = re.compile("[\t]")
匹配没有。
我建议,从更改elif inner.match(line):
为else:
推荐阅读
- html - div表的边框间距问题
- unit-testing - 如何检查 Java 8 Stream 是否关闭?
- php - codeigniter hook post并获取数据进行安全处理(SQL注入)
- r - 从 GRIB 文件中获取特定位置的数据
- ios - iOS Security.framework arm64 架构问题
- netlogo - 网络标志中的补丁可以有两种颜色,有时隐藏一种吗?
- css - 如何组合两个 SCSS 选择器?
- ios - 将字符串拆分为数组数组
- cloud - 当我想在 SAP Cloud Platform 中运行 UI5 应用程序时缺少功能的问题
- vba - 导入数据后刷新表单