python - 键和多行 python 值

标签 python string

我正在尝试读取文本文件或在具有以下结构的文件上使用 ConfigParser

        Index1 = '''You have been redirected to this page for one of the following 

        reasons:

        Either cookies are not enabled on your browser
        or
        Your network configuration is causing cookies to be lost or not function properly.
        IEEE Xplore requires cookies to maintain sessions and to access licensed content. Cookies are used temporarily to maintain sessions in 
        IEEE Xplore and for no other purpose.'''

        Index2 = '''Internet Explorer 6, 7, or 8
        Click Tools menu.
        Select Internet Options.
        Select Privacy tab. 
        Click the Default button or slide the bar down to 'Medium'.
        Click Ok. '''

我希望能够给它键值Index1并获取其后面的字符串 block ,或者迭代所有索引值并获取它们后面的 block 。我似乎无法从字符串中读取超过一行

到目前为止我已经尝试过

for line in fileinput.input('config.conf'):
    part = line.partition("'''")
    ts = part[0]
    st = part[1]

最佳答案

解决该问题的一种方法是拥有一个 config.ini 文件,例如

[Multiline Values]
Index1 : You have been redirected to this page for one of the following
    reasons:
    Either cookies are not enabled on your browser
    or
    Your network configuration is causing cookies to be lost or not function properly.
    IEEE Xplore requires cookies to maintain sessions and to access licensed content. Cookies are used temporarily to maintain sessions in
    IEEE Xplore and for no other purpose.

读起来像:

import ConfigParser
Config = ConfigParser.ConfigParser()
Config.read('config.ini')
val = Config.get('Multiline Values', 'Index1')
print val

输出:

You have been redirected to this page for one of the following
reasons:
Either cookies are not enabled on your browser
or
Your network configuration is causing cookies to be lost or not function properly.
IEEE Xplore requires cookies to maintain sessions and to access licensed content. Cookies are used temporarily to maintain sessions in
IEEE Xplore and for no other purpose.

header 名称“Multiline Values”和键名称“Index1”可以是任何内容。

关于python - 键和多行 python 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33743233/

相关文章:

python - 在 `for` 中使用 `print()` 会在 Python 3.x 上生成生成器吗?

python - 如何修复这个多线程 Python 脚本?

java - 将多行文本添加到 JTextArea

python - 从字符串列表中删除整数

c++ - 按数字和冒号验证字符串

javascript - 将 JavaScript 库移植到 Python

python - 无法使用 yapf(谷歌的 python 格式化程序)设置/使用旋钮

Java - 打印显示换行符的字符串

python - 使用 pandas 将字符串列连接到新列时出现问题吗?

Python 3 and-or vs if-else