从文本文件中提取数据以在python脚本中使用?

时间:2010-05-16 18:50:26

标签: python regex

基本上,我有一个这样的文件:

Url/Host:   www.example.com
Login:     user
Password:   password
Data_I_Dont_Need:    something_else

如何使用RegEx分隔细节以将其置于变量中?

对不起,如果这是一个可怕的问题,我可以永远不会掌握RegEx。所以另一个问题是,你能提供RegEx,但有什么解释它的每个部分是什么?

5 个答案:

答案 0 :(得分:1)

您应该将条目放在字典中,而不是放在很多单独的变量中 - 显然,您使用的密钥需要 NOT 作为变量名称(在“Url / Host”中斜杠) “会是一个杀手! - ),但它们会像字典中的字符串键一样好。

import re

there = re.compile(r'''(?x)      # verbose flag: allows comments & whitespace
                       ^         # anchor to the start
                       ([^:]+)   # group with 1+ non-colons, the key
                       :\s*      # colon, then arbitrary whitespace
                       (.*)      # group everything that follows
                       $         # anchor to the end
                    ''')

然后

 configdict = {}
 for aline in open('thefile.txt'):
   mo = there.match(aline)
   if not mo:
     print("Skipping invalid line %r" % aline)
     continue
   k, v = mo.groups()
   configdict[k] = v

将RE模式设为“详细”(通过使用(?x)启动或使用re.VERBOSE作为re.compile的第二个参数)的可能性非常有用,可以让您澄清您的RE评论和很好地对齐空白。我认为这很遗憾未被充分利用; - )。

答案 1 :(得分:1)

对于像这样简单的文件,您不需要正则表达式。字符串函数可能更容易理解。这段代码:

def parse(data):
    parsed = {}    
    for line in data.split('\n'):
        if not line: continue # Blank line
        pair = line.split(':')
        parsed[pair[0].strip()] = pair[1].strip()
    return parsed

if __name__ == '__main__':
    test = """Url/Host:   www.example.com
    Login:     user
    Password:   password
"""
    print parse(test)

将完成这项工作,并导致:

{'Login': 'user', 'Password': 'password', 'Url/Host': 'www.example.com'}

答案 2 :(得分:0)

好吧,如果您不了解正则表达式,只需更改您的文件:

Host = www.example.com
Login = uer
Password = password

并使用ConfigParser python模块http://docs.python.org/library/configparser.html

答案 3 :(得分:0)

编辑:更好的解决方案

for line in input: 
    key, val = re.search('(.*?):\s*(.*)', line).groups()

答案 4 :(得分:0)

ConfigParser模块支持':'分隔符。

import ConfigParser
from cStringIO import StringIO

class Parser(ConfigParser.RawConfigParser):
    def _read(self, fp, fpname):
        data = StringIO("[data]\n"+fp.read()) 
        return ConfigParser.RawConfigParser._read(self, data, fpname)

p = Parser()
p.read("file.txt")
print dict(p.items("data"))

输出:

{'login': 'user', 'password': 'password', 'url/host': 'www.example.com'}

虽然正则表达式或手动解析可能更适合你的情况。

相关问题