本文整理汇总了Python中pyparsing.Word方法的典型用法代码示例。如果您正苦于以下问题:Python pyparsing.Word方法的具体用法?Python pyparsing.Word怎么用?Python pyparsing.Word使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyparsing
的用法示例。
在下文中一共展示了pyparsing.Word方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __str__
# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Word [as 别名]
def __str__( self ):
try:
return super(Word,self).__str__()
except:
pass
if self.strRepr is None:
def charsAsStr(s):
if len(s)>4:
return s[:4]+"..."
else:
return s
if ( self.initCharsOrig != self.bodyCharsOrig ):
self.strRepr = "W:(%s,%s)" % ( charsAsStr(self.initCharsOrig), charsAsStr(self.bodyCharsOrig) )
else:
self.strRepr = "W:(%s)" % charsAsStr(self.initCharsOrig)
return self.strRepr
示例2: countedArray
# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Word [as 别名]
def countedArray( expr, intExpr=None ):
"""Helper to define a counted list of expressions.
This helper defines a pattern of the form::
integer expr expr expr...
where the leading integer tells how many expr expressions follow.
The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed.
"""
arrayExpr = Forward()
def countFieldParseAction(s,l,t):
n = t[0]
arrayExpr << (n and Group(And([expr]*n)) or Group(empty))
return []
if intExpr is None:
intExpr = Word(nums).setParseAction(lambda t:int(t[0]))
else:
intExpr = intExpr.copy()
intExpr.setName("arrayLen")
intExpr.addParseAction(countFieldParseAction, callDuringTry=True)
return ( intExpr + arrayExpr )
示例3: matchPreviousLiteral
# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Word [as 别名]
def matchPreviousLiteral(expr):
"""Helper to define an expression that is indirectly defined from
the tokens matched in a previous expression, that is, it looks
for a 'repeat' of a previous expression. For example::
first = Word(nums)
second = matchPreviousLiteral(first)
matchExpr = first + ":" + second
will match C{"1:1"}, but not C{"1:2"}. Because this matches a
previous literal, will also match the leading C{"1:1"} in C{"1:10"}.
If this is not desired, use C{matchPreviousExpr}.
Do *not* use with packrat parsing enabled.
"""
rep = Forward()
def copyTokenToRepeater(s,l,t):
if t:
if len(t) == 1:
rep << t[0]
else:
# flatten t tokens
tflat = _flatten(t.asList())
rep << And( [ Literal(tt) for tt in tflat ] )
else:
rep << Empty()
expr.addParseAction(copyTokenToRepeater, callDuringTry=True)
return rep
示例4: srange
# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Word [as 别名]
def srange(s):
r"""Helper to easily define string ranges for use in Word construction. Borrows
syntax from regexp '[]' string range definitions::
srange("[0-9]") -> "0123456789"
srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz"
srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_"
The input string must be enclosed in []'s, and the returned string is the expanded
character set joined into a single string.
The values enclosed in the []'s may be::
a single character
an escaped character with a leading backslash (such as \- or \])
an escaped hex character with a leading '\x' (\x21, which is a '!' character)
(\0x## is also supported for backwards compatibility)
an escaped octal character with a leading '\0' (\041, which is a '!' character)
a range of any of the above, separated by a dash ('a-z', etc.)
any combination of the above ('aeiouy', 'a-zA-Z0-9_$', etc.)
"""
_expanded = lambda p: p if not isinstance(p,ParseResults) else ''.join(unichr(c) for c in range(ord(p[0]),ord(p[1])+1))
try:
return "".join(_expanded(part) for part in _reBracketExpr.parseString(s).body)
except:
return ""
示例5: anything_beetween
# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Word [as 别名]
def anything_beetween(opener_and_closer):
"""Builds a (pyparsing) parser for the content inside delimiters.
Args:
opener_and_closer: a string containing two elements: opener and closer
Returns:
A (pyparsing) parser for the content inside delimiters.
"""
opener = pyparsing.Literal(opener_and_closer[0])
closer = pyparsing.Literal(opener_and_closer[1])
char_removal_mapping = dict.fromkeys(list(map(ord, opener_and_closer)))
other_chars = str(string.printable).translate(char_removal_mapping)
word_without_delimiters = pyparsing.Word(other_chars).setName(
"other_chars")
anything = pyparsing.Forward()
delimited_block = opener + anything + closer
# pylint: disable=expression-not-assigned
anything << pyparsing.ZeroOrMore(
word_without_delimiters.setName("word_without_delimiters")
| delimited_block.setName("delimited_block")
)
# Combine all the parts into a single string.
return pyparsing.Combine(anything)
示例6: countedArray
# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Word [as 别名]
def countedArray( expr, intExpr=None ):
"""Helper to define a counted list of expressions.
This helper defines a pattern of the form::
integer expr expr expr...
where the leading integer tells how many expr expressions follow.
The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed.
"""
arrayExpr = Forward()
def countFieldParseAction(s,l,t):
n = t[0]
arrayExpr << (n and Group(And([expr]*n)) or Group(empty))
return []
if intExpr is None:
intExpr = Word(nums).setParseAction(lambda t:int(t[0]))
else:
intExpr = intExpr.copy()
intExpr.setName("arrayLen")
intExpr.addParseAction(countFieldParseAction, callDuringTry=True)
return ( intExpr + arrayExpr ).setName('(len) ' + _ustr(expr) + '...')
示例7: getLogLineBNF
# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Word [as 别名]
def getLogLineBNF():
global logLineBNF
if logLineBNF is None:
integer = Word( nums )
ipAddress = delimitedList( integer, ".", combine=True )
timeZoneOffset = Word("+-",nums)
month = Word(string.uppercase, string.lowercase, exact=3)
serverDateTime = Group( Suppress("[") +
Combine( integer + "/" + month + "/" + integer +
":" + integer + ":" + integer + ":" + integer ) +
timeZoneOffset +
Suppress("]") )
logLineBNF = ( ipAddress.setResultsName("ipAddr") +
Suppress("-") +
("-" | Word( alphas+nums+"@._" )).setResultsName("auth") +
serverDateTime.setResultsName("timestamp") +
dblQuotedString.setResultsName("cmd").setParseAction(getCmdFields) +
(integer | "-").setResultsName("statusCode") +
(integer | "-").setResultsName("numBytesSent") +
dblQuotedString.setResultsName("referrer").setParseAction(removeQuotes) +
dblQuotedString.setResultsName("clientSfw").setParseAction(removeQuotes) )
return logLineBNF
示例8: _parse_filter
# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Word [as 别名]
def _parse_filter():
op = pyparsing.oneOf('! & |')
lpar = pyparsing.Literal('(').suppress()
rpar = pyparsing.Literal(')').suppress()
k = pyparsing.Word(pyparsing.alphanums)
# NOTE: We may need to expand on this list, but as this is not a real
# LDAP server we should be OK.
# Value to contain:
# numbers, upper/lower case letters, astrisk, at symbol, minus, full
# stop, backslash or a space
v = pyparsing.Word(pyparsing.alphanums + "-*@.\\ äöü")
rel = pyparsing.oneOf("= ~= >= <=")
expr = pyparsing.Forward()
atom = pyparsing.Group(lpar + op + expr + rpar) \
| pyparsing.Combine(lpar + k + rel + v + rpar)
expr << atom + pyparsing.ZeroOrMore( expr )
return expr
示例9: _globalParse___ssh_attributes
# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Word [as 别名]
def _globalParse___ssh_attributes(line):
ssh_dict = {}
ssh_option = (Word(alphas + '-'))('option')
ssh_value = (restOfLine) ('value')
result = (ssh_option + White() + ssh_value).parseString(line)
if result.option == 'logging':
ssh_dict['logging-events'] = 'yes'
elif result.option == 'authentication-retries':
ssh_dict['authentication_retries'] = result.value.split()[0]
elif result.option == 'port':
ssh_dict['port_rotary'] = result.value.split()[0]
elif result.option == 'maxstartups':
ssh_dict['maxstartups'] = result.value.split()[0]
elif result.option == 'time-out':
ssh_dict['time-out'] = result.value.split()[0]
elif result.option == 'version':
ssh_dict['version'] = result.value.split()[0]
return ssh_dict
示例10: _globalParse___username_attributes
# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Word [as 别名]
def _globalParse___username_attributes(line):
username_dict = {}
username = (Word(printables)) ('user')
privilege = (Suppress('privilege') + Word(nums)) ('priv_num')
password_type = (Suppress(MatchFirst(['secret', 'password'])) + Word(nums))('pass_type')
parse_username = username + Optional(privilege) + password_type + Suppress(restOfLine)
result = parse_username.parseString(line)
username_dict[result.user] = {}
username_dict[result.user]['password_type'] = result.pass_type.asList()[0]
try:
username_dict[result.user]['privilege'] = result.priv_num.asList()[0]
except AttributeError:
pass
return username_dict
示例11: __ifaceAttributes___storm_check
# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Word [as 别名]
def __ifaceAttributes___storm_check(storm,dct):
parse_level = Word(alphas) + Suppress('level ') + restOfLine
parse_action = Suppress('action ') + Word(alphas)
parse_type = Word(alphas) + Suppress(Optional("include")) + Word(alphas)
try:
value = parse_level.parseString(storm).asList()
if 'level' in dct:
dct['level'].append(value)
else:
dct['level'] = [value]
return dct
except ParseException:
pass
try:
return util.int_dict_parse(parse_action, storm, 'action', dct)
except ParseException:
pass
try:
return util.int_dict_parse(parse_type, storm, 'type', dct)
except ParseException:
pass
示例12: srange
# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Word [as 别名]
def srange(s):
r"""Helper to easily define string ranges for use in Word construction. Borrows
syntax from regexp '[]' string range definitions::
srange("[0-9]") -> "0123456789"
srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz"
srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_"
The input string must be enclosed in []'s, and the returned string is the expanded
character set joined into a single string.
The values enclosed in the []'s may be::
a single character
an escaped character with a leading backslash (such as \- or \])
an escaped hex character with a leading '\x' (\x21, which is a '!' character)
(\0x## is also supported for backwards compatibility)
an escaped octal character with a leading '\0' (\041, which is a '!' character)
a range of any of the above, separated by a dash ('a-z', etc.)
any combination of the above ('aeiouy', 'a-zA-Z0-9_$', etc.)
"""
try:
return "".join(_expanded(part) for part in _reBracketExpr.parseString(s).body)
except:
return ""