如何在Python中读取多行.properties文件

发布于 2024-11-06 11:41:22 字数 259 浏览 0 评论 0原文

我正在尝试读取 java 多行 i18n 属性文件。有如下行:

messages.welcome=Hello\
 World!
messages.bye=bye

使用此代码:

import configobj
properties = configobj.ConfigObj(propertyFileName)

但对于多行值,它会失败。

有什么建议吗?

I'm trying to read a java multiline i18n properties file. Having lines like:

messages.welcome=Hello\
 World!
messages.bye=bye

Using this code:

import configobj
properties = configobj.ConfigObj(propertyFileName)

But with multilines values it fails.

Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

寄居人 2024-11-13 11:41:22

根据 ConfigObj 文档configobj 要求您将多行值括在三引号中:

包含换行符的值
(多行值)可以被包围
通过三重引号。这些也可以
如果一个值包含两种类型,则使用
引号。名单成员不能
用三重引号括起来:

如果无法修改属性文件,我建议使用 configparser< /a>:

在配置解析器中,值可以跨越
多行,只要它们是
缩进比所持有的键多
他们。默认情况下解析器还让
空行作为值的一部分。

这是概念的快速证明:

#!/usr/bin/env python
# coding: utf-8

from __future__ import print_function

try:
    import ConfigParser as configparser
except ImportError:
    import configparser

try:
    import StringIO
except ImportError:
    import io.StringIO as StringIO

test_ini = """
[some_section]
messages.welcome=Hello\
 World
messages.bye=bye
"""
config = configparser.ConfigParser()
config.readfp(StringIO.StringIO(test_ini))
print(config.items('some_section'))

输出:

[('messages.welcome', 'Hello World'),
('messages.bye', '再见')]

According to the ConfigObj documentation, configobj requires you to surround multiline values in triple quotes:

Values that contain line breaks
(multi-line values) can be surrounded
by triple quotes. These can also be
used if a value contains both types of
quotes. List members cannot be
surrounded by triple quotes:

If modifying the properties file is out of the question, I suggest using configparser:

In config parsers, values can span
multiple lines as long as they are
indented more than the key that holds
them. By default parsers also let
empty lines to be parts of values.

Here's a quick proof of concept:

#!/usr/bin/env python
# coding: utf-8

from __future__ import print_function

try:
    import ConfigParser as configparser
except ImportError:
    import configparser

try:
    import StringIO
except ImportError:
    import io.StringIO as StringIO

test_ini = """
[some_section]
messages.welcome=Hello\
 World
messages.bye=bye
"""
config = configparser.ConfigParser()
config.readfp(StringIO.StringIO(test_ini))
print(config.items('some_section'))

Output:

[('messages.welcome', 'Hello World'),
('messages.bye', 'bye')]

天涯离梦残月幽梦 2024-11-13 11:41:22

感谢您的回答,这就是我最终所做的:

  • 将该部分添加到属性文件的第一行
  • 删除空
  • 行使用 configparser 进行解析
  • 删除第一行(在第一步中添加的部分)

这是代码的摘录:

#!/usr/bin/python
...
# Add the section
subprocess.Popen(['/bin/bash','-c','sed -i \'1i [default]\' '+srcDirectory+"/*.properties"], stdout=subprocess.PIPE)
# Remove empty lines
subprocess.Popen(['/bin/bash','-c','sed -i \'s/^$/#/g' '+srcDirectory+"/*.properties"], stdout=subprocess.PIPE)
# Get all i18n files
files=glob.glob(srcDirectory+"/"+baseFileName+"_*.properties")
config = ConfigParser.ConfigParser()
for propFile in files:
...
    config.read(propertyFileName)
    value=config.get('default',"someproperty")
...
# Remove section 
subprocess.Popen(['/bin/bash','-c','sed -i \'1d\' '+srcDirectory+"/*.properties"], stdout=subprocess.PIPE)

我仍然有那些不以空格开头的多行会出现问题。我只是手动修复了它们,但 sed 可以解决这个问题。

Thanks for the answers, this is what I finally did:

  • Add the section to the fist line of the properties file
  • Remove empty lines
  • Parse with configparser
  • Remove first line (section added in first step)

This is a extract of the code:

#!/usr/bin/python
...
# Add the section
subprocess.Popen(['/bin/bash','-c','sed -i \'1i [default]\' '+srcDirectory+"/*.properties"], stdout=subprocess.PIPE)
# Remove empty lines
subprocess.Popen(['/bin/bash','-c','sed -i \'s/^$/#/g' '+srcDirectory+"/*.properties"], stdout=subprocess.PIPE)
# Get all i18n files
files=glob.glob(srcDirectory+"/"+baseFileName+"_*.properties")
config = ConfigParser.ConfigParser()
for propFile in files:
...
    config.read(propertyFileName)
    value=config.get('default',"someproperty")
...
# Remove section 
subprocess.Popen(['/bin/bash','-c','sed -i \'1d\' '+srcDirectory+"/*.properties"], stdout=subprocess.PIPE)

I still have troubles with those multilines that doesn't start with an empty space. I just fixed them manually, but a sed could do the trick.

旧时光的容颜 2024-11-13 11:41:22

像这样设置属性文件的格式:

messages.welcome="""Hello
 World!"""
messages.bye=bye

Format your properties file like this:

messages.welcome="""Hello
 World!"""
messages.bye=bye
避讳 2024-11-13 11:41:22

Give a try to ConfigParser

霓裳挽歌倾城醉 2024-11-13 11:41:22

我不明白 Java 汤中的任何内容,但我希望正则表达式可以帮助您:

import re

ch = '''messages.welcome=Hello
  World!  
messages.bye=bye'''

regx = re.compile('^(messages\.[^= \t]+)[ \t]*=[ \t]*(.+?)(?=^messages\.|\Z)',re.MULTILINE|re.DOTALL)

print regx.findall(ch)

结果

[('messages.welcome', 'Hello\n  World!  \n'), ('messages.bye', 'bye')]

I don't understand anything in the Java broth, but a regex would help you, I hope:

import re

ch = '''messages.welcome=Hello
  World!  
messages.bye=bye'''

regx = re.compile('^(messages\.[^= \t]+)[ \t]*=[ \t]*(.+?)(?=^messages\.|\Z)',re.MULTILINE|re.DOTALL)

print regx.findall(ch)

result

[('messages.welcome', 'Hello\n  World!  \n'), ('messages.bye', 'bye')]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文