本文整理汇总了Python中string.count方法的典型用法代码示例。如果您正苦于以下问题:Python string.count方法的具体用法?Python string.count怎么用?Python string.count使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类string
的用法示例。
在下文中一共展示了string.count方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: count_words
# 需要导入模块: import string [as 别名]
# 或者: from string import count [as 别名]
def count_words(candidate_text, common_words=frequency.common_words['english'], case_sensitive=True):
'''
Count the instances of common words in the expected plaintext
language, return the total number of characters matched in each
word
candidate_text - (string) Sample to analyze
common_words - (list) Sequences expected to appear in the text
case_sensitive - (bool) Whether or not to match case sensitively
'''
score = 0
for word in common_words:
if not case_sensitive:
word = word.lower()
num_found = candidate_text.count(word)
if num_found > 0:
score += num_found * len(word)
return score
示例2: translateDescParams
# 需要导入模块: import string [as 别名]
# 或者: from string import count [as 别名]
def translateDescParams(desc_params):
desc_params = desc_params.replace(" ", "")
buff = ""
for elem in desc_params.split(","):
if elem != "":
tab = ""
if "[" in elem:
tab = "[" * string.count(elem, "[")
elem = elem[:tab.find("[") - 2]
if elem not in BASIC_TYPES:
if elem in ADVANCED_TYPES:
buff += tab + ADVANCED_TYPES[elem] + " "
else:
buff += tab + "L" + elem.replace(".", "/") + "; "
else:
buff += tab + BASIC_TYPES[elem] + " "
buff = buff[:-1]
return buff
示例3: translateDescReturn
# 需要导入模块: import string [as 别名]
# 或者: from string import count [as 别名]
def translateDescReturn(desc_return):
buff = ""
for elem in desc_return.split(" "):
tab = ""
if "[" in elem:
tab = "[" * string.count(elem, "[")
elem = elem[:tab.find("[") - 2]
if elem in BASIC_TYPES:
buff += tab + BASIC_TYPES[elem] + " "
else:
if elem in ADVANCED_TYPES:
buff += tab + ADVANCED_TYPES[elem] + " "
else:
if "." in elem:
buff += tab + "L" + elem.replace(".", "/") + "; "
buff = buff[:-1]
return buff
示例4: _getFragWord
# 需要导入模块: import string [as 别名]
# 或者: from string import count [as 别名]
def _getFragWord(frags,maxWidth):
''' given a fragment list return a list of lists
[size, spaces, (f00,w00), ..., (f0n,w0n)]
each pair f,w represents a style and some string
'''
W = []
n = 0
s = 0
for f in frags:
text = f.text[:]
W.append((f,text))
cb = getattr(f,'cbDefn',None)
if cb:
_w = getattr(cb,'width',0)
if hasattr(_w,'normalizedValue'):
_w._normalizer = maxWidth
n = n + stringWidth(text, f.fontName, f.fontSize)
#s = s + _countSpaces(text)
s = s + string.count(text, ' ') # much faster for many blanks
#del f.text # we can't do this until we sort out splitting
# of paragraphs
return n, s, W
示例5: ParseCSVLine
# 需要导入模块: import string [as 别名]
# 或者: from string import count [as 别名]
def ParseCSVLine(line):
line = line.strip()
values = []
while line.__len__() > 0:
if string.count(line, ',') > 0:
if line[0] == '"':
line = line[1:]
values.append(line[:string.find(line, '"')])
line = line[string.find(line, '"') + 1:]
line = line[1:]
if line.__len__() == 0:
values.append("")
else:
values.append(line[:string.find(line, ',')])
line = line[string.find(line, ',') + 1:]
if line.__len__() == 0:
values.append("")
else:
values.append(line)
line = ""
return values
示例6: domain_counter
# 需要导入模块: import string [as 别名]
# 或者: from string import count [as 别名]
def domain_counter(fqdn):
''' counter for domains based on the last two zones '''
fulldata = []
for each in fqdn:
a = count((each),".")
if a >= 2:
fulldata.append(each[::-1])
fulldata.sort()
domain_trunk = []
for each in fulldata:
splitdata = each.split('.')
# treat the first two as one
TwoZones = str(splitdata[0])+"."+str(splitdata[1])
#print TwoZones
domain_trunk.append(TwoZones)
fulldata = []
for each in domain_trunk:
fulldata.append(each[::-1])
return (Counter(fulldata))
示例7: ip_print
# 需要导入模块: import string [as 别名]
# 或者: from string import count [as 别名]
def ip_print(sublist):
query = r.hget('IP:'+str(sublist), 'name')
first = r.hget('IP:'+str(sublist), 'first')
date = r.hget('IP:'+str(sublist), 'date')
count = r.hget('IP:'+str(sublist), 'count')
rr_type = r.hget('IP:'+str(sublist), 'type')
ttl = r.hget('IP:'+str(sublist), 'ttl')
count = r.hget('IP:'+str(sublist), 'count')
#dns_client = r.hget(sublist, 'dns_client')
#dns_server = r.hget(sublist, 'dns_server')
#nss = r.hget(sublist, 'nss')
if first == None:
first = '00000000'
if date == None:
date = '00000000'
# PRINT FIELDS
print "{0:18} {1:35} {2:9} {3:9} {4:8} {5:8} {6:6}".format(sublist,query,first[:8],date[:8],record_translate(rr_type),ttl,count)
pass
示例8: unique
# 需要导入模块: import string [as 别名]
# 或者: from string import count [as 别名]
def unique(L):
noDupli=[]
[noDupli.append(i) for i in L if not noDupli.count(i)]
return noDupli
示例9: parseJavaScriptContent
# 需要导入模块: import string [as 别名]
# 或者: from string import count [as 别名]
def parseJavaScriptContent(jsContent):
global database_url, database_ext, dumb_params
"""
Parse the content of a JavaScript file
"""
for l in jsContent.readlines():
for e in allowed:
if l.count('.'+e) > 0:
# we found an external a call
if l.count('http://') > 0 and l.count(root) < 1:
# External link
et= '.'+e
b1 = l.find('http://')
b2 = l.find(et) + len(et)
database_ext.append(l[b1:b2])
else:
# Internal link
et= '.'+e
b2 = l.find(et) + len(et)
b1 = rfindFirstJSChars(l[:b2])+1
database_url.append(giveGoodURL(l[b1:b2],root))
# try to get a parameter
k = l.find('?')
if k > 0:
results = l[k:].split('?')
plop = []
for a in results:
plop.append(cleanListDumbParams(regDumbParam.split(a)))
dumb_params.append(flatten(plop))
k = l.find('&')
if k > 0:
results = l[k:].split('&')
plop = []
for a in results:
plop.append(cleanListDumbParams(regDumbParam.split(a)))
plop = flatten(plop)
dumb_params.append(flatten(plop))
dumb_params = unique(flatten(dumb_params))
示例10: generate_frequency_table
# 需要导入模块: import string [as 别名]
# 或者: from string import count [as 别名]
def generate_frequency_table(text,charset):
'''
Generate a character frequency table for a given text
and charset as dict with character or string as key and
frequency of appearance as value expressed as a decimal
percentage
text - A sample of plaintext to analyze for frequency data
charset - (list of strings) The set of items to count in the plaintext
such as ['a','b','c', ... 'z','aa','ab','ac', ... 'zz']
'''
freq_table = {}
text_len = 0
for char in charset:
freq_table[char] = 0
for char in text:
if char in charset:
freq_table[char] += 1
text_len += 1
for multigraph in filter(lambda x: len(x)>1,charset):
freq_table[multigraph] = string.count(text, multigraph)
# Normalize frequencies with length of text
for key in freq_table.keys():
if text_len != 0:
freq_table[key] /= float(text_len)
else:
freq_table[key] = 0
return freq_table
示例11: format_error
# 需要导入模块: import string [as 别名]
# 或者: from string import count [as 别名]
def format_error(input, err, scanner):
"""This is a really dumb long function to print error messages nicely."""
error_message = StringIO.StringIO()
p = err.pos
print >> error_message, "error position", p
# Figure out the line number
line = count(input[:p], '\n')
print >> error_message, err.msg, "on line", repr(line+1) + ":"
# Now try printing part of the line
text = input[max(p-80, 0):p+80]
p = p - max(p-80, 0)
# Strip to the left
i = rfind(text[:p], '\n')
j = rfind(text[:p], '\r')
if i < 0 or (0 <= j < i): i = j
if 0 <= i < p:
p = p - i - 1
text = text[i+1:]
# Strip to the right
i = find(text,'\n', p)
j = find(text,'\r', p)
if i < 0 or (0 <= j < i):
i = j
if i >= 0:
text = text[:i]
# Now shorten the text
while len(text) > 70 and p > 60:
# Cut off 10 chars
text = "..." + text[10:]
p = p - 7
# Now print the string, along with an indicator
print >> error_message, '> ', text.replace('\t', ' ').encode(sys.getdefaultencoding())
print >> error_message, '> ', ' '*p + '^'
print >> error_message, 'List of nearby tokens:', scanner
return error_message.getvalue()
示例12: wrap_error_reporter
# 需要导入模块: import string [as 别名]
# 或者: from string import count [as 别名]
def wrap_error_reporter(parser, rule):
try:
return getattr(parser, rule)()
except SyntaxError, e:
logging.exception('syntax error')
input = parser._scanner.input
try:
error_msg = format_error(input, e, parser._scanner)
except ImportError:
error_msg = 'Syntax Error %s on line\n' % (e.msg, 1 + count(input[:e.pos]))
示例13: _countSpaces
# 需要导入模块: import string [as 别名]
# 或者: from string import count [as 别名]
def _countSpaces(text):
return string.count(text, ' ')
## i = 0
## s = 0
## while 1:
## j = string.find(text,' ',i)
## if j<0: return s
## s = s + 1
## i = j + 1
示例14: LoadBlocks
# 需要导入模块: import string [as 别名]
# 或者: from string import count [as 别名]
def LoadBlocks(path):
global blocks
with open(path) as f:
count = 0
for line in f:
count += 1
if count < 3:
continue
blocks.append(ParseCSVLine(line))
blocks = sorted(blocks, key=lambda it: int(it[0]))
示例15: LoadLocations
# 需要导入模块: import string [as 别名]
# 或者: from string import count [as 别名]
def LoadLocations(path):
global locations
with open(path) as f:
count = 0
for line in f:
count += 1
if count < 3:
continue
(locId, country, region, city, postalCode, latitude, longitude,
metroCode, areaCode) = ParseCSVLine(line)
locations[int(locId)] = {"country": country, "region": region,
"city": city, "postalCode": postalCode, "latitude": latitude,
"longitude": longitude, "metroCode": metroCode,
"areaCode": areaCode}