本文整理汇总了Python中string.expandtabs函数的典型用法代码示例。如果您正苦于以下问题:Python expandtabs函数的具体用法?Python expandtabs怎么用?Python expandtabs使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了expandtabs函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: FormatOutput
def FormatOutput(beta_zero, beta_one,
correlation_r, correlation_square_r,
estimated_proxy_size=False, prediction=False):
'''
OutPut whit the optimal Format.
Parameters
-------
beta_zero: float,
Beta Zero
beta_one: float,
Beta One
correlation_r: float,
Correlation Index R
correlation_square_r: float,
Square Correlation Index R
estimated_proxy_size: float,
Estimated Proxy Size
prediction: float,
Prediction for estimated_proxy_size
'''
#Print Header
print "===================================================================="
print string.expandtabs("BetaZero\tBetaOne\tCorrelation R\tCorrelation R^2",
16)
print "===================================================================="
#Print Values
print string.expandtabs("%s\t%s\t%s\t%s" % (
beta_zero,beta_one,
correlation_r,correlation_square_r)
,16)
print "===================================================================="
if estimated_proxy_size and prediction:
print ("For E=%s The prediction is P=%s" %
(estimated_proxy_size, prediction))
示例2: get_playerNames
def get_playerNames(numPlayers, playerNames_hum, playerNames_comp):
players = ["Player 1", "Player 2", "Player 3"]
print string.center(("-" * 80), 80)
print string.center(("-" * 80), 80)
for i in range(numPlayers):
name = ""
while name == "":
name = raw_input(players[i] + ", what is your name? ")
name = name.title()
if name == "":
print string.center(("-" * 80), 80)
print string.center(("-" * 80), 80)
print string.expandtabs("ERROR, FIELD EMPTY")
print string.expandtabs("Please try again.")
print string.center(("-" * 80), 80)
print string.center(("-" * 80), 80)
players[i] = name
if numPlayers == 3:
print string.center(("-" * 80), 80)
print "Welcome", players[0] + ",", players[1] + ", and", players[2] + "!"
if numPlayers == 2:
players[2] = playerNames_comp[0]
print string.center(("-" * 80), 80)
print "Welcome", players[0] + " and", players[1] + "! Today you will be playing against", players[2] + "."
if numPlayers == 1:
players[1] = playerNames_comp[0]
players[2] = playerNames_comp[1]
print string.center(("-" * 80), 80)
print "Welcome", players[0] + "! Today you will be playing against", players[1], "and", players[2] + "."
return players
示例3: LOCCountDir
def LOCCountDir(root, extensions=PY_EXTENSION):
'''
Locate all files matching supplied filename pattern in and below
supplied root directory.
Parameters
----------
root : str, path of programs
search file for counting lines..
extensions : list, List of extensions
Extension to search programs
'''
locate = LocateFiles(root, extensions)
great_total = 0
while True:
try:
file_to_count = locate.next()
log.info("Counting File: %s" % file_to_count)
(code_lines, parts, total_lines, blank_lines, comment_lines)=LOCCountFile(file_to_count)
#print "===================================================================="
print string.expandtabs("\t%s" % file_to_count.split("/")[-1],16)
FormatOutput(code_lines, parts, total_lines, blank_lines, comment_lines)
great_total+=code_lines
except StopIteration:
log.info("Fin De Archivado")
break
print "===================================================================="
print string.expandtabs("TOTAL\t\t\t%s" % great_total,16)
print "===================================================================="
示例4: send_literal_data
def send_literal_data(self, data):
if not data:
return
lines = string.splitfields(data, '\n')
text = string.expandtabs(lines[0])
for l in lines[1:]:
self.OutputLine(text, 1)
text = string.expandtabs(l)
self.OutputLine(text, 0)
self.atbreak = 0
示例5: parseJR
def parseJR(fwReport):
try:
print fwReport
lfnText = None
pfnText = None
guid = None
doc = xml.dom.minidom.parse(fwReport)
#get the output LFN
fileNode = doc.getElementsByTagName('File')
#print fileNode[0].toxml()
print fileNode
if ( fileNode is not None ):
print len(fileNode)
print type(fileNode)
fileNode = fileNode[0]
lfnNode = fileNode.getElementsByTagName('LFN')
print 'lfnNode %s' % lfnNode
if ( lfnNode is not None):
lfnText = getText(lfnNode[0].childNodes)
#replace all tabs with 0 space
lfnText = expandtabs(lfnText, 0)
lfnText = lfnText.replace('\n','')
#pfnNode = xpath.Evaluate('descendant::File/PFN', doc.documentElement)
pfnNode = fileNode.getElementsByTagName('PFN')
print 'pfnNode %s ' % pfnNode
if ( pfnNode is not None):
pfnText = getText(pfnNode[0].childNodes)
pfnText = expandtabs(pfnText, 0)
pfnText = pfnText.replace('\n','')
#guidNode = xpath.Evaluate('descendant::File/GUID', doc.documentElement)
guidNode = fileNode.getElementsByTagName('GUID')
#print 'guidNode %s' % guidNode
if ( guidNode is not None):
guid = getText(guidNode[0].childNodes)
guid = expandtabs(guid, 0)
guid = guid.replace('\n','')
#print 'LFN: %s' % lfnText
#print 'PFN: %s' % pfnText
#print 'GUID: %s' % guid
return {'LFN':lfnText, 'PFN': pfnText, 'GUID': guid}
except:
print 'problem addToDataCache:%s, %s' % \
(sys.exc_info()[0], sys.exc_info()[1])
traceback.print_exc(file=sys.stdout)
return {'Error':'Parse_Error'}
示例6: getcomments
def getcomments(object):
"""Get lines of comments immediately preceding an object's source code.
Returns None when source can't be found.
"""
try:
lines, lnum = findsource(object)
except (IOError, TypeError):
return None
if ismodule(object):
start = 0
if lines and lines[0][:2] == '#!':
start = 1
while start < len(lines) and string.strip(lines[start]) in ('', '#'):
start = start + 1
if start < len(lines) and lines[start][:1] == '#':
comments = []
end = start
while end < len(lines) and lines[end][:1] == '#':
comments.append(string.expandtabs(lines[end]))
end = end + 1
return string.join(comments, '')
elif lnum > 0:
indent = indentsize(lines[lnum])
end = lnum - 1
if end >= 0 and string.lstrip(lines[end])[:1] == '#' and indentsize(lines[end]) == indent:
comments = [string.lstrip(string.expandtabs(lines[end]))]
if end > 0:
end = end - 1
comment = string.lstrip(string.expandtabs(lines[end]))
while comment[:1] == '#' and indentsize(lines[end]) == indent:
comments[:0] = [comment]
end = end - 1
if end < 0:
break
comment = string.lstrip(string.expandtabs(lines[end]))
while comments and string.strip(comments[0]) == '#':
comments[:1] = []
while comments and string.strip(comments[-1]) == '#':
comments[-1:] = []
return string.join(comments, '')
return None
示例7: reformat_paragraph
def reformat_paragraph(data, limit=70):
lines = string.split(data, "\n")
i = 0
n = len(lines)
while i < n and is_all_white(lines[i]):
i = i+1
if i >= n:
return data
indent1 = get_indent(lines[i])
if i+1 < n and not is_all_white(lines[i+1]):
indent2 = get_indent(lines[i+1])
else:
indent2 = indent1
new = lines[:i]
partial = indent1
while i < n and not is_all_white(lines[i]):
# XXX Should take double space after period (etc.) into account
words = re.split("(\s+)", lines[i])
for j in range(0, len(words), 2):
word = words[j]
if not word:
continue # Can happen when line ends in whitespace
if len(string.expandtabs(partial + word)) > limit and \
partial != indent1:
new.append(string.rstrip(partial))
partial = indent2
partial = partial + word + " "
if j+1 < len(words) and words[j+1] != " ":
partial = partial + " "
i = i+1
new.append(string.rstrip(partial))
# XXX Should reformat remaining paragraphs as well
new.extend(lines[i:])
return string.join(new, "\n")
示例8: smart_indent_event
def smart_indent_event(self, event):
# if intraline selection:
# delete it
# elif multiline selection:
# do indent-region & return
# indent one level
text = self.text
first, last = self.editwin.get_selection_indices()
text.undo_block_start()
try:
if first and last:
if index2line(first) != index2line(last):
return self.indent_region_event(event)
text.delete(first, last)
text.mark_set("insert", first)
prefix = text.get("insert linestart", "insert")
raw, effective = classifyws(prefix, self.tabwidth)
if raw == len(prefix):
# only whitespace to the left
self.reindent_to(effective + self.indentwidth)
else:
if self.usetabs:
pad = '\t'
else:
effective = len(string.expandtabs(prefix,
self.tabwidth))
n = self.indentwidth
pad = ' ' * (n - effective % n)
text.insert("insert", pad)
text.see("insert")
return "break"
finally:
text.undo_block_stop()
示例9: run
def run(self, edit, width=0):
width = get_width(self.view)
settings = self.view.settings()
# Make sure tabs are handled as per the current buffer
tab_width = 8
if settings.get("tab_size", False):
try:
tab_width = int(self.view.settings().get("tab_size"))
except TypeError:
pass
if tab_width == 0:
tab_width == 8
paragraphs = []
for s in self.view.sel():
#self.view.insert(edit, s.begin(), self.MARKER)
paragraphs.extend(
par.all_paragraphs_intersecting_selection(self.view, s))
if len(paragraphs) > 0:
self.view.sel().clear()
for p in paragraphs:
self.view.sel().add(p)
# This isn't an ideal way to do it, as we loose the position of the
# cursor within the paragraph: hence why the paragraph is selected
# at the end.
for s in self.view.sel():
wrapper = textwrap.TextWrapper()
wrapper.expand_tabs = False
wrapper.replace_whitespace = settings.get(
'replace_whitespace', True)
wrapper.drop_whitespace = settings.get(
'drop_whitespace', True)
wrapper.width = width
prefix = self.extract_prefix(s)
if prefix:
wrapper.initial_indent = prefix[0]
wrapper.subsequent_indent = prefix[1]
wrapper.width -= self.width_in_spaces(prefix, tab_width)
if wrapper.width < 0:
continue
txt = self.view.substr(s)
if prefix:
txt = txt.replace(prefix[0], u"")
txt = string.expandtabs(txt, tab_width)
txt = wrapper.fill(txt) + u"\n"
self.view.replace(edit, s, txt)
# It's unhelpful to have the entire paragraph selected, just leave the
# selection at the end
ends = [s.end() - 1 for s in self.view.sel()]
self.view.sel().clear()
for pt in ends:
self.view.sel().add(sublime.Region(pt))
示例10: __init__
def __init__(self, filename, title, out = sys.stdout):
""" Store the source text.
"""
raw = file(filename).read()
self.title = title
self.raw = string.strip(string.expandtabs(raw))
self.out = out
示例11: __init__
def __init__( self, raw, output = sys.stdout, color_mapping = _colors ):
""" Store the source text"""
self._colors = color_mapping
self._outfile = output
self._raw = string.strip(string.expandtabs(raw))
示例12: __init__
def __init__(self,line,name=None,detectorname='',level=None,signature=None,inpnum=None,dimnum=None,configured=None,edge=None,delay=None,deltamin=None,deltamax=None):
if line=='':
self.name = name
self.detectorname = detectorname
self.level = level
self.signature = signature
self.inpnum = inpnum
self.dimnum = dimnum
self.configured = configured
self.edge = edge
self.delay = delay
self.deltamin = deltamin
self.deltamax = deltamax
self.l0fdefinition = None
return
self.line = line
self.name = None
self.detectorname = None
self.level = None
self.signature = None
self.inpnum = None
self.dimnum = None
self.configured = None
self.l0fdefinition = None
self.edge = 0
self.delay = 0
self.deltamin = 1000
self.deltamax = 1000
# parse line (extract input name)
self.line = string.expandtabs(self.line)
self.line = string.strip(self.line,'\n')
ninps = string.split(self.line,'=')
if len(ninps)!=2:
PrintError("CTP input definition (or detector it belongs to) missing for "+line)
return
self.name = string.strip(ninps[0])
if self.name[:3]=='l0f' or self.name[:3]=='l0A' or self.name[:3]=='l0B':
self.l0fdefinition = string.strip(ninps[1])
return
# parse the remaining line (input description)
li = string.split(ninps[1],' ')
for ix in range(len(li)-1, -1, -1):
if li[ix]=='': del li[ix]
self.detectorname = li[0]
if len(li) == 1:
self.configured = 0
elif len(li) >= 9:
self.level = int(li[1])
self.signature = int(li[2])
self.inpnum = int(li[3])
self.dimnum = int(li[4])
self.configured = int(li[5])
# elif len(li) >= 9:
self.edge = int(li[6])
self.delay = int(li[7])
self.deltamin = int(li[8])
self.deltamax = int(li[9])
else:
PrintError("Bad CTP input definition:"+line)
示例13: adjust_whitespace
def adjust_whitespace(text):
"""remove the left-whitespace margin of a block of Python code."""
state = [False, False]
(backslashed, triplequoted) = (0, 1)
def in_multi_line(line):
current_state = state[backslashed] or state[triplequoted]
if re.search(r"\\$", line):
state[backslashed] = True
else:
state[backslashed] = False
line = re.split(r"#", line)[0]
triples = len(re.findall(r"\"\"\"|\'\'\'", line))
if triples == 1 or triples % 2 != 0:
state[triplequoted] = not state[triplequoted]
return current_state
def _indent_line(line, stripspace=""):
return re.sub(r"^%s" % stripspace, "", line)
stream = StringIO()
stripspace = None
for line in re.split(r"\r?\n", text):
if in_multi_line(line):
stream.write(line + "\n")
else:
line = string.expandtabs(line)
if stripspace is None and re.search(r"^[ \t]*[^# \t]", line):
stripspace = re.match(r"^([ \t]*)", line).group(1)
stream.write(_indent_line(line, stripspace) + "\n")
return stream.getvalue()
示例14: __getCalls
def __getCalls(self, lines):
"""returns a tuple containing the list of defined subroutines and
the list of used subroutines of a fortran source file
Return
defined : a list of subroutine defined in the fortran source code
used : a list of subroutine that are used by the code
included : a list of things included in the code
"""
used = []
for lsave in lines:
l=string.expandtabs(string.lower(lsave)[:-1],1)
words=string.split(string.lstrip(l))
if len(words) > 0:
if (words[0][0] == '!'):
continue
for i in range(len(words)-1):
if words[i] == 'call':
name = string.split(words[i+1],'(')[0]
used.append(name)
# We delete all dependencies that are present several number of times.
used = list(set(used))
return used
示例15: collect_paras
def collect_paras(lines):
paras = []
line_number = 1
lineacc = []
previndent = None
for line in lines:
line = string.expandtabs(string.rstrip(line, '\r\n'))
(prefix, line) = _ws_prefix_re.match(line).groups()
indent = len(prefix)
if previndent is None: previndent = indent
if previndent != indent or not line:
if lineacc: paras.append(Paragraph(previndent, prevline_number, lineacc))
previndent = indent
lineacc = []
if line:
if not lineacc: prevline_number = line_number
lineacc.append(line)
line_number = line_number + 1
if lineacc:
paras.append(Paragraph(previndent, prevline_number, lineacc))
return paras