Python从属性文件中获取多行值



我有一个包含多行的属性文件,其中一些值在不止一行上。类似这样的东西:

first.key=
Right,
Side,
Value
second.key=Second value
third.key=Third value

我想取每个键的值。我不能预处理文件,所以我不能用三引号或其他任何东西括起来。所以,如果我想把每个键和值放在一个列表中的文件行中,比如:

for line in file:
split = line.split('=')

然后获取密钥和值

key = split[0]
value = split[1]
print(key) -> first.key
print(value) -> Right,Side,Value

for line in file:
while line.endswith('\'):
line += next(file)
will give me TypeError: 'list' object is not an iterator

请记住,属性文件的每一行都是列表中的一项。我可以为每一行提取关键点和值,但我很难用多行值来实现这一点。如果前一行.ends为('\'(,我可能应该在前一行后面加上下一行,但我想不通。编辑。['multiline.key=值的第一行\','Second line of the value','Third line of the value \','Fourth line of the val','Fifth line of the value \','aother.key=Some value','Some.key=another value']我知道如何应对'other.key=某个值','Some.key=另一个值'

我不知道如何提取单一值:

First line of the value\', 'Second line of the value\', 'Third 
line of the value\', 'Fourth line of the value\', 'Fifth line of 
the value\'

for多重密钥

文件如下:

multiline.key=First line of the value
Second line of the value
Third line of the value
Fourth line of the value
Fifth line of the value
another.key=Some value
some.key=Another value

预期结果:

1st key=multiline.key
1st value=First line of the valueSecond line of the valueThird 
line of the valueFourth line of the valueFifth line of the value
2nd key=another.key
2nd value=Some value
3rd key=some.key
3rd value=Another value
属性文件与INI文件完全相同。

您可以使用带有伪段的configparser来轻松解析它:

data = r"""first.key=
Right,
Side,
Value
second.key=Second value
third.key=Third value"""
import configparser
def read_properties(data: str):
config = configparser.ConfigParser()
config.read_string("[dummysection]n" + data)
return dict(config['dummysection'])
print(read_properties(data))

输出:

{'first.key': '\nRight,\nSide,\nValue', 'second.key': 'Second value', 'third.key': 'Third value'}

如果您愿意,您可以进一步处理它以删除\n:

print({k: v.replace("\n", "") for k, v in read_properties(data).items()})

输出:

{'first.key': 'Right,Side,Value', 'second.key': 'Second value', 'third.key': 'Third value'}

如果您不想使用配置解析器,我编写了一个自定义解析器

import re
with open('delete.txt', "r") as file:
data = file.read()
# parsed_data = data.split('=')
parsed_data = re.split('(?<=[^\\])n', data)
data_dict = {}
for element in parsed_data:
split = element.split('=')
data_dict[split[0]] = split[1].split('\n')
for key in data_dict:
print(f"{key} : {data_dict[key]}")

输出:

first.key : ['', '        Right,', '        Side,', '        Value']
second.key : ['Second value']
third.key : ['Third value']

这个解析器肯定可以改进。但我想说,最困难的部分已经被解决了

输入文件:

first.key=
Right,
Side,
Value
second.key=Second value
third.key=Third value

这会有帮助吗?

输入文件";多行.txt";

first.key=
Right,
Side,
Value
second.key=Second value
third.key=Third value

代码

  • 创建了一个名为keyvals的空字典
  • 如果一行包含=,则通过拆分获得键值对
  • 如果一行不包含=,则将该行附加到上一个值
keyvals = {}
lines= open('multiline.txt', mode='r').read().splitlines()
for line in lines:
if '=' in line:
split = line.split('=')
keyvals[split[0]] = split[1].replace('\','').strip()
else:
keyvals[split[0]] += line.replace('\','').strip()
print(keyvals)

注意:
splitlines((处理换行符n
strip((删除文本前后的额外空格或制表符。

输出:

{'first.key': 'Right,Side,Value', 'second.key': 'Second value', 'third.key': 'Third value'}

最新更新