本文整理汇总了Python中string.expandtabs函数的典型用法代码示例。如果您正苦于以下问题:Python expandtabs函数的具体用法?Python expandtabs怎么用?Python expandtabs使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了expandtabs函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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))
开发者ID:arpagon,项目名称:assignaments,代码行数:35,代码来源:fit.py
示例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
开发者ID:churchie317,项目名称:wheel_of_fortune,代码行数:30,代码来源:Wheel_of_Fortune_v1.py
示例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 "===================================================================="
开发者ID:arpagon,项目名称:assignaments,代码行数:29,代码来源:pyloc.py
示例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
开发者ID:CKannas,项目名称:rdkit,代码行数:10,代码来源:HTMLPiddler.py
示例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'}
开发者ID:zhiwenuil,项目名称:WMCore,代码行数:49,代码来源:PilotJob.py
示例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
开发者ID:webiumsk,项目名称:WOT-0.9.15.1,代码行数:48,代码来源:inspect.py
示例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")
开发者ID:alexei-matveev,项目名称:ccp1gui,代码行数:34,代码来源:FormatParagraph.py
示例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()
开发者ID:Claruarius,项目名称:stblinux-2.6.37,代码行数:33,代码来源:AutoIndent.py
示例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))
开发者ID:jngeist,项目名称:MarkdownHardWrap,代码行数:60,代码来源:hard_wrap_markdown_lines.py
示例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
开发者ID:auag92,项目名称:n2dm,代码行数:7,代码来源:Color.py
示例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))
开发者ID:nm13,项目名称:throwaway-code,代码行数:7,代码来源:colorize.py
示例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)
开发者ID:AakaFosfor,项目名称:trigger,代码行数:60,代码来源:switched.py
示例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()
开发者ID:OleksiyPuzikov,项目名称:shaderman,代码行数:32,代码来源:pygen.py
示例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
开发者ID:Autiwa,项目名称:autiwa-py-modules,代码行数:28,代码来源:fortranSource.py
示例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
开发者ID:Codesleuth,项目名称:rabbitmq-dotnet-client,代码行数:27,代码来源:Block.py
示例16: histUser
def histUser(self, userId, userIdtoSearch):
self._log.info("user:" + userId + " command:histImg args={userIdtoSearch:" + userIdtoSearch + "}")
output = {}
output ['head'] = "User Id Used Disk \t\t Last Login \t\t #Owned Images \n"
output ['head'] = string.expandtabs(output ['head'], 8)
stradd = ""
for i in range(len(output['head'])):
stradd += "-"
output ['head'] += stradd
if (userIdtoSearch == "None"):
userIdtoSearch = None
users = self.userStore.queryStore(userId, userIdtoSearch)
if(users != None):
for key in users.keys():
spaces = ""
num = 8 - len(users[key]._userId)
if (num > 0):
for i in range(num):
spaces += " "
output[key] = users[key]._userId + spaces + " " + str(users[key]._fsUsed).split(".")[0] + " \t\t " + \
str(users[key]._lastLogin) + " \t " + str(users[key]._ownedImgs).split(".")[0] + "\n"
return output
开发者ID:futuregrid,项目名称:rain2-donotuse,代码行数:28,代码来源:IRService.py
示例17: generate_assigns_buffer
def generate_assigns_buffer(invert_reset, bindings, internal_bindings, debug=False):
buf = ""
if len(internal_bindings) > 0:
buf += "//Internal Bindings\n"
for key in internal_bindings:
if key == "clk":
continue
if key == "rst":
continue
if key == internal_bindings[key]["signal"]:
continue
buf += "assign\t{0:<20}=\t{1};\n".format(key, internal_bindings[key]["signal"])
buf += "\n\n"
if len(bindings) > 0:
buf += "//Bindings\n"
buf += "always @ (*) begin\n"
for key in bindings:
if key == "clk":
continue
if key == "rst":
continue
if key == bindings[key]["loc"]:
continue
if (bindings[key]["direction"] == "input") and ("reg" in bindings[key]):
buf += "\t{0:<20}=\t{1};\n".format(key, bindings[key]["loc"])
#buf += "assign\t{0:<20}=\t{1};\n".format(key, bindings[key]["loc"])
buf += "end\n"
for key in bindings:
if key == "clk":
continue
if key == "rst":
continue
if key == bindings[key]["loc"]:
continue
if (bindings[key]["direction"] == "input") and ("reg" not in bindings[key]):
buf += "assign\t{0:<20}=\t{1};\n".format(key, bindings[key]["loc"])
for key in bindings:
if key == bindings[key]["loc"]:
continue
if bindings[key]["direction"] == "output":
buf += "assign\t{0:<20}=\t{1};\n".format(bindings[key]["loc"], key)
if invert_reset:
buf += "\n"
buf += "//Invert Reset for this board\n"
buf += "always @ (*) begin\n"
buf += "\t{0:<20}=\t{1};\n".format("rst_n", "~rst")
buf += "end\n"
return string.expandtabs(buf, 2)
开发者ID:CospanDesign,项目名称:nysa,代码行数:60,代码来源:sim_utils.py
示例18: __init__
def __init__(self, raw):
""" Store the source text. """
self.out_lines = []
for line in string.strip(string.expandtabs(raw)).split('\n'):
self.raw = line
self.out = ""
self.out_lines += [self.format(None, None)]
开发者ID:cart0113,项目名称:catalystlc,代码行数:7,代码来源:pycode_to_html.py
示例19: scrub_asm_x86
def scrub_asm_x86(asm, args):
# Scrub runs of whitespace out of the assembly, but leave the leading
# whitespace in place.
asm = common.SCRUB_WHITESPACE_RE.sub(r' ', asm)
# Expand the tabs used for indentation.
asm = string.expandtabs(asm, 2)
# Detect shuffle asm comments and hide the operands in favor of the comments.
asm = SCRUB_X86_SHUFFLES_RE.sub(r'\1 {{.*#+}} \2', asm)
# Detect stack spills and reloads and hide their exact offset and whether
# they used the stack pointer or frame pointer.
asm = SCRUB_X86_SPILL_RELOAD_RE.sub(r'{{[-0-9]+}}(%\1{{[sb]}}p)\2', asm)
# Generically match the stack offset of a memory operand.
asm = SCRUB_X86_SP_RE.sub(r'{{[0-9]+}}(%\1)', asm)
if getattr(args, 'x86_scrub_rip', False):
# Generically match a RIP-relative memory operand.
asm = SCRUB_X86_RIP_RE.sub(r'{{.*}}(%rip)', asm)
# Generically match a LCP symbol.
asm = SCRUB_X86_LCP_RE.sub(r'{{\.LCPI.*}}', asm)
if getattr(args, 'extra_scrub', False):
# Avoid generating different checks for 32- and 64-bit because of 'retl' vs 'retq'.
asm = SCRUB_X86_RET_RE.sub(r'ret{{[l|q]}}', asm)
# Strip kill operands inserted into the asm.
asm = common.SCRUB_KILL_COMMENT_RE.sub('', asm)
# Strip trailing whitespace.
asm = common.SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm)
return asm
开发者ID:bkaradzic,项目名称:SwiftShader,代码行数:26,代码来源:asm.py
示例20: cleandoc
def cleandoc(doc):
try:
lines = string.split(string.expandtabs(doc), '\n')
except UnicodeError:
return None
margin = sys.maxint
for line in lines[1:]:
content = len(string.lstrip(line))
if content:
indent = len(line) - content
margin = min(margin, indent)
if lines:
lines[0] = lines[0].lstrip()
if margin < sys.maxint:
for i in range(1, len(lines)):
lines[i] = lines[i][margin:]
while lines and not lines[-1]:
lines.pop()
while lines and not lines[0]:
lines.pop(0)
return string.join(lines, '\n')
开发者ID:Pluckyduck,项目名称:eve,代码行数:26,代码来源:inspect.py
注:本文中的string.expandtabs函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论