当前位置: 首页>>代码示例>>Python>>正文


Python string.capwords函数代码示例

本文整理汇总了Python中string.capwords函数的典型用法代码示例。如果您正苦于以下问题:Python capwords函数的具体用法?Python capwords怎么用?Python capwords使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了capwords函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __setitem__

 def __setitem__(self, i, y):
     self.regexIsDirty = True
     # for each entry the user adds, we actually add three entrys:
  
     super(WordSub,self).__setitem__(string.lower(i),string.lower(y)) # key = value
     super(WordSub,self).__setitem__(string.capwords(i), string.capwords(y)) # Key = Value
     super(WordSub,self).__setitem__(string.upper(i), string.upper(y)) # K
开发者ID:hitflame,项目名称:AntAIML,代码行数:7,代码来源:WordSub.py

示例2: format_data

    def format_data(self, data):
        for item in data['results']:
            item['visitor_name'] = string.capwords(item.get('namefirst', ''))
            if item.get('namemid', '') != '':
                item['visitor_name'] += " " + item.get('namemid', '') + "."
            item['visitor_name'] += " " + string.capwords(item.get('namelast', ''))
            item['visited_name'] = string.capwords(item.get('visitee_namefirst', ''))
            if string.capwords(item.get('visitee_namelast', '')) != 'And':
                item['visited_name'] += " " + string.capwords(item.get('visitee_namelast', ''))
            if item['visited_name'].rstrip().lstrip() == 'Potus':
                item['visited_name'] = 'The President'
            item['description'] = item.get('description', '').lower()

            led = item.get('lastentrydate', '')
            dd = DATE_PATTERN.match(led)
            if dd:
                dd = dd.groupdict()
                year = int(dd['year'])
                # yes, this is how I'm doing this
                if year < 2000:
                    year += 2000
                if dd['hour'] != None and dd['minute'] != None:
                    dt = datetime.datetime(year, int(dd['month']), int(dd['day']), int(dd['hour']), int(dd['minute']))

                    # will fail on systems with non-GNU C libs (i.e. Windows) due to %- removal of zero-padding
                    item['lastentry_date'] = dt.strftime('%-m-%-d-%Y %-I:%M %p')
                else:
                    dt = datetime.datetime(year, int(dd['month']), int(dd['day']))

                    item['lastentry_date'] = dt.strftime('%-m-%-d-%Y')
            else:
                item['lastentry_date'] = led

        return data
开发者ID:chriszs,项目名称:dataomega,代码行数:34,代码来源:white_house_logs.py

示例3: gather_teams

def gather_teams(years):
        """Gathers team names and ID numbers in the specified league"""
        for year in years:
		url = "http://games.espn.go.com/ffl/standings?leagueId=%s&seasonId=%s" % (args.league, year)
        	ourUrl = opener.open(url).read()
	        soup = BeautifulSoup(ourUrl)
		for num,division in enumerate(soup.findAll(bgcolor = '#ffffff', id = re.compile(r'\d'))):
	        	for i in division.findAll('tr', {'class' : 'evenRow bodyCopy sortableRow'}):
				title = i.find('td').text
				owner = string.capwords(title[title.find("(")+1:title.find(")")])
				pf = i.find('td', {'class': 'sortablePF'}).text
				pa = i.find('td', {'class': 'sortablePA'}).text
		                parsed = urlparse.urlparse(i.a['href']) #parse url parameters
        		        id = urlparse.parse_qs(parsed.query)['teamId'][0]
	                	name = i.a.text
		                teams.append(TeamID(name,owner,int(id),pf,pa,year,num+1))
			for i in division.findAll('tr', {'class' : 'oddRow bodyCopy sortableRow'}):
				title = i.find('td').text
		                owner = string.capwords(title[title.find("(")+1:title.find(")")])
        		        pf = i.find('td', {'class': 'sortablePF'}).text
                		pa = i.find('td', {'class': 'sortablePA'}).text
				parsed = urlparse.urlparse(i.a['href']) #parse url parameters
	        	        id = urlparse.parse_qs(parsed.query)['teamId'][0]
        	        	name = i.a.text
                		teams.append(TeamID(name,owner,int(id),pf,pa,year,num+1))
开发者ID:rbarton65,项目名称:ESPN-FFL-Analyzer,代码行数:25,代码来源:gather.py

示例4: __name__

 def __name__(self):
     feat_name = []
     for m1 in self.aggregation_mode_prev:
         for m in self.aggregation_mode:
             n = "EditDistance_%s_%s_%s"%(self.ngram_str, string.capwords(m1), string.capwords(m))
             feat_name.append(n)
     return feat_name
开发者ID:Anhmike,项目名称:Kaggle_HomeDepot,代码行数:7,代码来源:feature_distance.py

示例5: search_results

    def search_results(self, mood, query):
        tokens = tokenize(query)
        counts = defaultdict(int)
        for token in tokens:
            counts[token] += 1
        query_tf = defaultdict(float)
        for token, count in counts.iteritems():
            query_tf[token] = self._term_tf_idf(token, count)
        # magnitude
        mag = lambda x: math.sqrt(sum(i ** 2 for i in x))
        m = mag(query_tf.values())

        for token, count in query_tf.iteritems():
            if m != 0:
                query_tf[token] = count / m
            else:
                query_tf[token] = 0
        moodlist = []
        for song in self.song_list:
            if song["mood"] == mood:
                moodlist.append(song)
        moodcosinelist = []
        for song in moodlist:
            cosine = sum([query_tf[term] * song["tfidf"].get(term, 0) for term in query_tf.keys()])
            moodcosinelist.append(
                {"song": string.capwords(song["title"]), "cosine": cosine, "artist": string.capwords(song["artist"])}
            )
        neighbors = heapq.nlargest(10, moodcosinelist, key=operator.itemgetter("cosine"))
        if neighbors == []:
            neighbors = moodlist[:10]
        return neighbors
开发者ID:blink753,项目名称:470moodytunes,代码行数:31,代码来源:knn.py

示例6: main

def main():
    santas = assign_santas(read_families(sys.argv[1]))
    f = open("santas_list.txt", "w")
    for s in santas.items():
        f.write(string.capwords(s[0]) + " is a Santa for " + string.capwords(s[1]))
        f.write("\n")
    check_santas(santas, read_families(sys.argv[1]))
开发者ID:danielclarke,项目名称:secret-santa,代码行数:7,代码来源:secret_santa.py

示例7: insertIntoDict

def insertIntoDict(k, v, aDict):
	key = string.capwords(k)
	value = string.capwords(v)
	if key not in aDict:
		aDict[key] = [value]
	else: 
		aDict[key].append(value)
开发者ID:mcdermz,项目名称:Kate-s-Cookbooks,代码行数:7,代码来源:cookbookbeta_7.py

示例8: check_for_extra_permit_files

 def check_for_extra_permit_files():
     extra_permits = set()
     permits = glob('apps/regional/static/permits/*/*')
     for permit in permits:
         permit = re.sub('apps/regional/static/permits/', '', permit)
         state = permit[:2].upper()
         if re.match('city', permit[3:]):
             city = re.sub('city-|-all|-residential|-commercial|.pdf', '', permit[3:])
             city = string.capwords(re.sub('-', ' ', city))
             zipcode = Region.objects.filter(city=city, state=state)[0].zipcode
             permit = get_permit(zipcode, 'residential')
             if not permit or not permit.get('url'):
                 extra_permits.add('%s, %s' % (city, state))
         elif re.match('county', permit[3:]):
             county = re.sub('county-|-all|-residential|-commercial|.pdf', '', permit[3:])
             county = string.capwords(re.sub('-', ' ', county))
             zipcode = Region.objects.filter(county=county, state=state)[0].zipcode
             permit = get_permit(zipcode, 'residential')
             if not permit or not permit.get('url'):
                 extra_permits.add('%s, %s' % (county, state))
     extra_permits = list(extra_permits)
     extra_permits.sort()
     with open(path.join(path.dirname(__file__), 'extra_permits.txt'), 'w') as out:
         for permit in extra_permits:
             out.write('%s\n' % permit)
开发者ID:ryanwellman,项目名称:trashboard,代码行数:25,代码来源:full.py

示例9: save

	def save(self, *args, **kwargs):
		super(Workday, self).save(*args, **kwargs)
		if self.active:
			desc = "%s sjekket inn!" % capwords(self.slave.get_full_name())
		else:
			desc = "%s sjekket ut!" % capwords(self.slave.get_full_name())
		Activity(desc=desc, workday=self).save()
开发者ID:martolini,项目名称:kybtracksme,代码行数:7,代码来源:models.py

示例10: delete_button_click

 def delete_button_click(self):
     search = self.delete_combo_box.currentText()
     text = self.delete_line_edit.text()
     if search == 'ISBN':
         if not(Validations.is_valid_isbn(text)):
             QMessageBox(QMessageBox.Critical, "Error",
                         "Invalid ISBN. Please correct it!").exec_()
         books = select_by_isbn(text)
         if books != []:
             delete_by_isbn(text)
             QMessageBox(QMessageBox.Information, "Information",
                         "You successfully deleted this book!").exec_()
             return
         else:
             QMessageBox(QMessageBox.Information, "No results",
                         "There is NO such book in the library!").exec_()
             return
     elif search == 'Title':
         books = select_by_title(string.capwords(text))
         if books != []:
             delete_by_title(string.capwords(text))
             QMessageBox(QMessageBox.Information, "Information",
                         "You successfully deleted this book!").exec_()
             return
         else:
             QMessageBox(QMessageBox.Information, "No results",
                         "There is NO such book in the library!").exec_()
             return
开发者ID:DenitsaKostova,项目名称:Bookoholic,代码行数:28,代码来源:delete_book.py

示例11: menu

 def menu(n):
     if fg.get()=='1' or fg.get()=='0':
         m[0][0]=fg.get()
     if fg1.get()=='1' or fg1.get()=='0':
         m[0][1]=fg1.get()
     if fg2.get()=='1' or fg2.get()=='0':
         m[0][2]=fg2.get()
     if fg3.get()=='1' or fg3.get()=='0':
         m[1][0]=fg3.get()
     if fg4.get()=='1' or fg4.get()=='0':
         m[1][1]=fg4.get()
     if fg5.get()=='1' or fg5.get()=='0':
         m[1][2]=fg5.get()
     if fg6.get()=='1' or fg6.get()=='0':
         m[2][0]=fg6.get()
     if fg7.get()=='1' or fg7.get()=='0':
         m[2][1]=fg7.get()
     if fg8.get()=='1' or fg8.get()=='0':
         m[2][2]=fg8.get()
     gana=jugada()
     if gana=='0':
         tkMessageBox.showinfo("Felicitaciones!", "Ha Ganado el Jugador "+capwords(jugador1.get()))
     elif gana=='1':
         tkMessageBox.showinfo("Felicitaciones!", "Ha Ganado el Jugador "+capwords(jugador2.get()))
     else:
         f=0
         for i in m:
             if i==2:
                 f+=1
         if f==0:
             tkMessageBox.showinfo("Empate", "Jugada Terminada")
开发者ID:Nestor01,项目名称:python,代码行数:31,代码来源:Juego_triqui.py

示例12: __setitem__

 def __setitem__(self, i, y):
     #print "set item: %s,%s" %(i,y)
     self._regexIsDirty = True
     # for each entry the user adds, we actually add three entrys:
     super(type(self),self).__setitem__(string.lower(i),string.lower(y)) # key = value
     super(type(self),self).__setitem__(string.capwords(i), string.capwords(y)) # Key = Value
     super(type(self),self).__setitem__(string.upper(i), string.upper(y)) # KEY = VALUE
开发者ID:jannson,项目名称:rivescript-python,代码行数:7,代码来源:wordsub.py

示例13: get_job_metadata

 def get_job_metadata(self, page):
     """Collect metadata for extractor-job"""
     group  = ""
     gtype  = ""
     series = ""
     _     , pos = text.extract(page, '<h1><a href="/reader/', '')
     title , pos = text.extract(page, '.html">', "</a>", pos)
     _     , pos = text.extract(page, '<li><a href="/artist/', '', pos)
     artist, pos = text.extract(page, '.html">', '</a>', pos)
     test  , pos = text.extract(page, '<li><a href="/group/', '', pos)
     if test is not None:
         group , pos = text.extract(page, '.html">', '</a>', pos)
     test  , pos = text.extract(page, '<a href="/type/', '', pos)
     if test is not None:
         gtype , pos = text.extract(page, '.html">', '</a>', pos)
     _     , pos = text.extract(page, '<tdLanguage</td>', '', pos)
     lang  , pos = text.extract(page, '.html">', '</a>', pos)
     test  , pos = text.extract(page, '<a href="/series/', '', pos)
     if test is not None:
         series, pos = text.extract(page, '.html">', '</a>', pos)
     lang = lang.capitalize()
     return {
         "category": self.category,
         "gallery-id": self.gid,
         "title": title,
         "artist": string.capwords(artist),
         "group": string.capwords(group),
         "type": gtype[1:-1].capitalize(),
         "lang": iso639_1.language_to_code(lang),
         "language": lang,
         "series": string.capwords(series),
     }
开发者ID:gcomyn,项目名称:gallery-dl,代码行数:32,代码来源:hitomi.py

示例14: Send_Images

def Send_Images(bot, chat_id, user, requestText, args, keyConfig, total_number_to_send=1):
    data, total_results, results_this_page = Google_Custom_Search(args)
    if 'items' in data and total_results > 0:
        total_offset, total_results, total_sent = search_results_walker(args, bot, chat_id, data, total_number_to_send,
                                                                        user + ', ' + requestText, results_this_page,
                                                                        total_results, keyConfig)
        if int(total_sent) < int(total_number_to_send):
            if int(total_number_to_send) > 1:
                bot.sendMessage(chat_id=chat_id, text='I\'m sorry ' + (user if not user == '' else 'Dave') +
                                                      ', I\'m afraid I can\'t find any more images for ' +
                                                      string.capwords(requestText.encode('utf-8') + '.' +
                                                                      ' I could only find ' + str(
                                                          total_sent) + ' out of ' + str(total_number_to_send)))
            else:
                bot.sendMessage(chat_id=chat_id, text='I\'m sorry ' + (user if not user == '' else 'Dave') +
                                                      ', I\'m afraid I can\'t find any images for ' +
                                                      string.capwords(requestText.encode('utf-8')))
        else:
            return True
    else:
        if 'error' in data:
            bot.sendMessage(chat_id=chat_id, text='I\'m sorry ' + (user if not user == '' else 'Dave') +
                                                  data['error']['message'])
        else:
            bot.sendMessage(chat_id=chat_id, text='I\'m sorry ' + (user if not user == '' else 'Dave') +
                                                  ', I\'m afraid I can\'t find any images for ' +
                                                  string.capwords(requestText.encode('utf-8')))
开发者ID:SalamiArmy,项目名称:Thorin,代码行数:27,代码来源:get.py

示例15: _do_write

 def _do_write(fname, variable, version, date, table):
     print("writing {} ..".format(fname))
     import unicodedata
     import datetime
     import string
     utc_now = datetime.datetime.now(tz=datetime.timezone.utc)
     INDENT = 4
     with open(fname, 'w') as fp:
         fp.write("# Generated: {iso_utc}\n"
                  "# Source: {version}\n"
                  "# Date: {date}\n"
                  "{variable} = (".format(iso_utc=utc_now.isoformat(),
                                          version=version,
                                          date=date,
                                          variable=variable))
         for start, end in table:
             ucs_start, ucs_end = unichr(start), unichr(end)
             hex_start, hex_end = ('0x{0:04x}'.format(start),
                                   '0x{0:04x}'.format(end))
             try:
                 name_start = string.capwords(unicodedata.name(ucs_start))
             except ValueError:
                 name_start = u''
             try:
                 name_end = string.capwords(unicodedata.name(ucs_end))
             except ValueError:
                 name_end = u''
             fp.write('\n' + (' ' * INDENT))
             fp.write('({0}, {1},),'.format(hex_start, hex_end))
             fp.write('  # {0:24s}..{1}'.format(
                 name_start[:24].rstrip() or '(nil)',
                 name_end[:24].rstrip()))
         fp.write('\n)\n')
     print("complete.")
开发者ID:thomasballinger,项目名称:wcwidth,代码行数:34,代码来源:setup.py


注:本文中的string.capwords函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。