def assemble(instrs):
res = []
for inst in instrs:
m = instre.match(inst)
if not m or not m.group(1) in aCode_map:
continue
opcode, parmfmt = aCode_map[m.group(1)]
res.append(struct.pack("B", opcode))
if m.group(2):
if parmfmt == 0:
continue
parms = [int(x) for x in re.split(",\s*", m.group(2))]
if parmfmt == -1:
l = len(parms)
res.append(struct.pack(("%dB" % (l+1)), l, *parms))
else:
res.append(struct.pack(parmfmt, *parms))
return b"".join(res)
python类split()的实例源码
def fromXML(self, name, attrs, content, ttFont, version=2.0):
if name == 'linearClasses':
for element in content:
if not isinstance(element, tuple): continue
tag, attrs, subcontent = element
if tag == 'linear':
l = content_string(subcontent).split()
self.linear.append(l)
elif name == 'nonLinearClasses':
for element in content:
if not isinstance(element, tuple): continue
tag, attrs, subcontent = element
if tag =='nonLinear':
l = {}
for e in subcontent:
if not isinstance(e, tuple): continue
tag, attrs, subsubcontent = e
if tag == 'map':
l[attrs['glyph']] = int(safeEval(attrs['index']))
self.nonLinear.append(l)
def collect_moves(self, reader, name):
Moves = namedtuple('Moves', ['pokemon', 'gen', 'color', 'moves', 'versions'])
if name.split('-')[-1].isdigit():
for row in reader:
if name == row[0]:
pokemon = name.split('-')[0].title()
generation, color = switcher[row[1]], int(ast.literal_eval(row[2]))
moves, versions = ast.literal_eval(row[3]), ast.literal_eval(row[4])
return Moves(pokemon, generation, color, moves, versions)
else:
for row in reader:
if name in row[0]:
pokemon = name.title()
generation, color = switcher[row[1]], int(ast.literal_eval(row[2]))
moves, versions = ast.literal_eval(row[3]), ast.literal_eval(row[4])
return Moves(pokemon, generation, color, moves, versions)
def clean_recipient_numbers(self):
cleaned_numbers = []
error_numbers = []
# 0?? ???? ?? 9? ?? 10?? ???? ??
p = re.compile(r'^0\d{9}\d?$')
number_string = self.cleaned_data['recipient_numbers']
print(number_string)
# ???? ?? '-'??? ''(? ???)? ?????
sub_string = re.sub(r'\s|-', '', number_string)
print(sub_string)
# , ?? .? ???? ???? ??? ???? ??? numbers? ??
numbers = re.split(r',|\.', sub_string)
print(numbers)
for number in numbers:
if re.match(p, number):
cleaned_numbers.append(number)
else:
error_numbers.append(number)
if error_numbers:
raise ValidationError('Invalid phone number format! {}'.format(', '.join(error_numbers)))
return cleaned_numbers
def _custom(self, custom):
"""
Create commented files to let the admin know where it's safe
to make custom changes. Mirror the default tree. Never overwrite.
"""
path_dir = os.path.dirname(custom)
if not os.path.isdir(path_dir):
_create_dirs(path_dir, self.pillar_dir)
if not self.dryrun:
if not os.path.isfile(custom):
log.info("Writing {}".format(custom))
with open(custom, "w") as yml:
custom_split = custom.split("stack")
custom_for = "{}{}{}".format(
custom_split[0],
"stack/default",
custom_split[1])
yml.write("# {}\n".format(custom))
yml.write("# Overwrites configuration in {}\n".format(custom_for))
_examples(custom, yml)
def _parse(line):
"""
Return globbed files constrained by optional slices or regexes.
"""
if " " in line:
parts = re.split('\s+', line)
files = sorted(glob.glob(parts[0]))
for optional in parts[1:]:
filter_type, value = optional.split('=')
if filter_type == "re":
regex = re.compile(value)
files = [m.group(0) for l in files for m in [regex.search(l)] if m]
elif filter_type == "slice":
# pylint: disable=eval-used
files = eval("files{}".format(value))
else:
log.warning("keyword {} unsupported".format(filter_type))
else:
files = glob.glob(line)
return files
def _parse(self, line):
"""
Return globbed files constrained by optional slices or regexes.
"""
if " " in line:
parts = re.split(r'\s+', line)
files = sorted(glob.glob(parts[0]))
for keyvalue in parts[1:]:
key, value = keyvalue.split('=')
if key == "re":
regex = re.compile(value)
files = [match.group(0) for _file in files
for match in [regex.search(_file)] if match]
elif key == "slice":
# pylint: disable=eval-used
files = eval("files{}".format(value))
else:
log.warning("keyword {} unsupported".format(key))
else:
files = glob.glob(line)
return files
def prep_blob(self, blob):
"""Cleanup input."""
# remove empty lines
if type(blob) == list:
blob = [line for line in blob if line.strip() != '']
if len(blob) == 1:
blob = blob[0].replace('\\n', '\n').split('\n')
# Split by line
if type(blob) == str or type(blob) == six.text_type:
lines = blob.split('\n')
elif type(blob) == list:
if len(blob) == 1:
lines = blob[0].split('\n')
else:
lines = [line.rstrip() for line in blob]
else:
message = "Unknown input format"
log.debug("%s - '%s", message, blob)
raise ParseException(message)
return lines
def _save_edgelist_as_1_indexed(f_edgelist, f_target_edgelist, delimiter="\t"):
"""
Note that this function always saves with delimiter "\t"
:param f_edgelist:
:param f_target_edgelist:
:param delimiter:
:return:
"""
import re
with open(f_target_edgelist, "w") as g:
with open(f_edgelist, "r") as f:
for line in f:
line = line.replace('\r', '').replace('\n', '')
edge = re.split(delimiter, line)
try:
g.write(str(int(edge[0]) + 1) + "\t" + str(int(edge[1]) + 1) + "\n")
except ValueError as e:
raise ValueError(
"[ERROR] Please check if the delimiter for the edgelist file is wrong -- {}".format(e)
)
def _setup_requirements(argument):
from sqlalchemy.testing import config
from sqlalchemy import testing
if config.requirements is not None:
return
modname, clsname = argument.split(":")
# importlib.import_module() only introduced in 2.7, a little
# late
mod = __import__(modname)
for component in modname.split(".")[1:]:
mod = getattr(mod, component)
req_cls = getattr(mod, clsname)
config.requirements = testing.requires = req_cls()
def _setup_requirements(argument):
from alembic.testing import config
if config.requirements is not None:
return
modname, clsname = argument.split(":")
# importlib.import_module() only introduced in 2.7, a little
# late
mod = __import__(modname)
for component in modname.split(".")[1:]:
mod = getattr(mod, component)
req_cls = getattr(mod, clsname)
config.requirements = req_cls()
def push(self, data):
"""Push some new data into this object."""
# Handle any previous leftovers
data, self._partial = self._partial + data, ''
# Crack into lines, but preserve the newlines on the end of each
parts = NLCRE_crack.split(data)
# The *ahem* interesting behaviour of re.split when supplied grouping
# parentheses is that the last element of the resulting list is the
# data after the final RE. In the case of a NL/CR terminated string,
# this is the empty string.
self._partial = parts.pop()
# parts is a list of strings, alternating between the line contents
# and the eol character(s). Gather up a list of lines after
# re-attaching the newlines.
lines = []
for i in range(len(parts) // 2):
lines.append(parts[i*2] + parts[i*2+1])
self.pushlines(lines)
def parse_tags(self, root):
ans = []
exclude_tokens = {'kindle', 'a-z'}
exclude = {'special features', 'by authors', 'authors & illustrators', 'books', 'new; used & rental textbooks'}
seen = set()
for a in root.xpath(self.tags_xpath):
raw = (a.text or '').strip().replace(',', ';').replace('/', ';').replace('>', ';')
lraw = icu_lower(raw)
tokens = frozenset(lraw.split())
if raw and lraw not in exclude and not tokens.intersection(exclude_tokens) and lraw not in seen:
ans.append(raw)
seen.add(lraw)
return ans
def unquote_unreserved(uri):
"""Un-escape any percent-escape sequences in a URI that are unreserved
characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
:rtype: str
"""
parts = uri.split('%')
for i in range(1, len(parts)):
h = parts[i][0:2]
if len(h) == 2 and h.isalnum():
try:
c = chr(int(h, 16))
except ValueError:
raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)
if c in UNRESERVED_SET:
parts[i] = c + parts[i][2:]
else:
parts[i] = '%' + parts[i]
else:
parts[i] = '%' + parts[i]
return ''.join(parts)
def unquote_unreserved(uri):
"""Un-escape any percent-escape sequences in a URI that are unreserved
characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
"""
parts = uri.split('%')
for i in range(1, len(parts)):
h = parts[i][0:2]
if len(h) == 2 and h.isalnum():
try:
c = chr(int(h, 16))
except ValueError:
raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)
if c in UNRESERVED_SET:
parts[i] = c + parts[i][2:]
else:
parts[i] = '%' + parts[i]
else:
parts[i] = '%' + parts[i]
return ''.join(parts)
def is_valid_cidr(string_network):
"""Very simple check of the cidr format in no_proxy variable"""
if string_network.count('/') == 1:
try:
mask = int(string_network.split('/')[1])
except ValueError:
return False
if mask < 1 or mask > 32:
return False
try:
socket.inet_aton(string_network.split('/')[0])
except socket.error:
return False
else:
return False
return True
def fix_repeating_arguments(self):
"""Fix elements that should accumulate/increment values."""
either = [list(c.children) for c in self.either.children]
for case in either:
for e in [c for c in case if case.count(c) > 1]:
if type(e) is Argument or type(e) is Option and e.argcount:
if e.value is None:
e.value = []
elif type(e.value) is not list:
e.value = e.value.split()
if type(e) is Command or type(e) is Option and e.argcount == 0:
e.value = 0
return self
def parse(class_, option_description):
short, long, argcount, value = None, None, 0, False
options, _, description = option_description.strip().partition(' ')
options = options.replace(',', ' ').replace('=', ' ')
for s in options.split():
if s.startswith('--'):
long = s
elif s.startswith('-'):
short = s
else:
argcount = 1
if argcount:
matched = re.findall('\[default: (.*)\]', description, flags=re.I)
value = matched[0] if matched else None
return class_(short, long, argcount, value)
def __init__(self, source, error):
self += source.split() if hasattr(source, 'split') else source
self.error = error
def parse_defaults(doc):
# in python < 2.7 you can't pass flags=re.MULTILINE
split = re.split('\n *(<\S+?>|-\S+?)', doc)[1:]
split = [s1 + s2 for s1, s2 in zip(split[::2], split[1::2])]
options = [Option.parse(s) for s in split if s.startswith('-')]
#arguments = [Argument.parse(s) for s in split if s.startswith('<')]
#return options, arguments
return options