2017-04-19 82 views
1

我正试图使用​​Python的解析库解析日志。 (https://pypi.python.org/pypi/parse)出于我的目的,我需要在格式字符串中使用类型说明符,但是,我解析的一些数据可能是几种类型的组合。使用Python解析来获取一串数字,字母,空白和符号

例如:

"4.56|test-1 Cool|dog" 

我可以分析使用“狗”末格式指示符克(一般号)和W(字)的前部的数量。然而,中间短语“test-1 Cool”是一个数字,字母,空格和短划线。单独使用任何说明符似乎都不起作用(尝试过W,w,s和S)。我想将这个短语解释为一个字符串。

没有问题句话,我只是这样做:

test = "|4.56|dog|" 
result = parse('|{number:g}|{word:w}|', test) 

编辑:我已经使用自定义类型转换一些成功如下图所示:

def SString(string): 
    return string 

test = "|4.56|test-1 Cool|dog|" 
result = parse('|{number:g}|{other:SString}|{word:w}|', test, dict(SString=SString)) 

回答

2

你可以用这样的代码做到这一点:

from parse import * 

test = "4.56|test-1 Cool|dog" 
result = parse('{number:g}|{other}|{word:w}', test) 
print result 
#<Result() {'other': 'test-1 Cool', 'word': 'dog', 'number': 4.56}> 

另外,对于类型检查,你可以使用re模块(例如):

from parse import * 
import re 

def SString(string): 
    if re.match('\w+-\d+ \w+',string): 
     return string 
    else: 
     return None 

test = "|4.56|test-1 Cool|dog|" 
result = parse('|{number:g}|{other:SString}|{word:w}|', test, dict(SString=SString)) 
print(result) 
#<Result() {'other': 'test-1 Cool', 'word': 'dog', 'number': 4.56}> 

test = "|4.56|t3est Cool|dog|" 
result = parse('|{number:g}|{other:SString}|{word:w}|', test, dict(SString=SString)) 
print(result) 
#<Result() {'other': None, 'word': 'dog', 'number': 4.56}> 
+0

这将是伟大的,但我真的需要类型说明符才能告诉用户想要的类型,因为用户输入了分析字符串。我目前使用自定义类型转换,它似乎是工作正常,我会将其添加到我原来的帖子 –

+0

@SethDavis现在检查我的答案 – RaminNietzsche

+0

谢谢!虽然,看起来re.match行预计实际上可能是几种不同的格式,但不包含空格或数字。 “test 1-cool”“cool1 -test”“cool-test”应该都是一样的,只是把它作为一个字符串返回。我只是希望整个事情作为一个字符串,用一个类型说明符告诉我期望一个字符串。我相信自定义类型转换对此非常适用,但将其引入到re库中非常有用 –

1

关于尝试

如何
test.split("|") 
+0

用于解析字符串是因为它很容易有一个配置文件,编辑,也是类型说明符更方便是有用的,因为数据将被发送到数据库,这意味着我需要知道每个片段应该是什么类型,以便数据类型和列的类型匹配 –