• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python string.capwords函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: add_parts

def add_parts(words):
        indi_mangled = []
        mangled = []
        mangled_fupper = []
        mangled_upper = [word[:1].upper() + word[1:] for word in words]
        mangled_lower = [word[:1].lower() + word[1:] for word in words]
        mangled_prep = [word[:1].lower() + word[1:] for word in words]
        for s in itertools.permutations(mangled_upper, 3):
                mangled.append(''.join(s))
        for s in itertools.permutations(mangled_lower, 3):
                mangled.append(''.join(s))
        for s in itertools.permutations(mangled_prep, 3):
                mangled_fupper.append(''.join(s))
        for s in mangled_fupper:
                mangled.append(string.capwords(s))
        for word in words:
                mangled.append(word)
        
        for s in itertools.permutations(mangled_upper, 2):
                indi_mangled.append(''.join(s))
        for s in itertools.permutations(mangled_lower, 2):
                indi_mangled.append(''.join(s))
        for s in itertools.permutations(mangled_prep, 2):
                indi_mangled.append(''.join(s))
        for s in mangled_fupper:
                indi_mangled.append(string.capwords(s))
        for word in words:
                indi_mangled.append(word)
                
        joined_list = mangled + indi_mangled
        
        return joined_list
开发者ID:darryllane,项目名称:Jenny,代码行数:32,代码来源:Jen.py


示例17: run

    def run(self, name):
        if name != 'you':
            print(string.capwords("fuck you {}!".format(name)), end='\n\n')
            return

        print(string.capwords("fuck you!"), end='\n\n')
        return
开发者ID:studiomezklador,项目名称:flask_restful1,代码行数:7,代码来源:manage.py


示例18: format_answers

 def format_answers(answers):
     print 'Answers:'
     number = 0
     for answer in answers:
         number += 1          
         answers = string_replace(regexes[3], "", str(number) + '.' + answer.replace(":", ""))
         print string.capwords(answers)
开发者ID:gkokaisel,项目名称:Miscellaneous-,代码行数:7,代码来源:respondus_converter.py


示例19: revise_stopname

def revise_stopname(stopname):
    # we ALWAYS want to apply these
    place_substitutions1 = [
        ('\[[^\[\]]+\] ?', ''),
        ('and *$', ''), # trailing ands...
        ]
    for subst in place_substitutions1:
        stopname = re.sub(subst[0], subst[1], stopname)

    # replace '... <...> CIVIC XX' w/ 'Near XX ...'
    m = re.match('(.+) (in front of|before|after|opposite|before and opposite) civic address ([0-9]+)', stopname)
    if m:
        return "Near %s %s" % (m.group(3), string.capwords(m.group(1)))

    boring_street_suffixes = [ "Ave", "Blvd", "Cr", "Crt", "Ct", "Dr", "Gate", "Pkwy", "Rd", "Row", 
                               "St" ]
    boring_street_regex = '(?:' + '|'.join(boring_street_suffixes) + ')'
    def strip_boring_street_suffix(text):
        m = re.match('(.*) ' + boring_street_regex, text)
        if m:
            return m.group(1)

        return text

    street_suffixes = boring_street_suffixes + [ "Hwy", "Terr" ]
    street_regex = '(?:' + '|'.join(street_suffixes) + ')'

    m = re.match('^(.*) ' + street_regex + ' (after|before|opposite|in front of) (.*) ' + street_regex + '$', stopname)
    if m:
        return "%s & %s" % (string.capwords(strip_boring_street_suffix(m.group(1))), 
                            string.capwords(strip_boring_street_suffix(m.group(3))))

    return string.capwords(stopname)
开发者ID:wlach,项目名称:routez,代码行数:33,代码来源:update-halifax-gtfs.py


示例20: load_files

def load_files(culture):
    # Process Zip Codes
    all_zips = {}
    reader = csv.reader(open(os.path.join(data_dir, culture, "zip-codes.txt"), "rb"))
    for row in reader:
        data = [string.capwords(row[3]), row[4]]
        all_zips[row[0]] = data
    output = open('source-data.pkl', 'wb')
    pickle.dump(all_zips, output)

    #Process area codes
    area_code_file = open(os.path.join(data_dir, culture, "area-codes.txt"), "rb")
    state_area_codes = {}
    for line in area_code_file:
        clean_line = line.replace(' ','').rstrip('\n')
        state_area_codes[line.split(':')[0]] = clean_line[3:].split(',')
    pickle.dump(state_area_codes, output)
    area_code_file.close()

    #Process Last Names
    last_names = []
    last_name_file = open(os.path.join(data_dir, culture, "last-name.txt"),"rb")
    for line in last_name_file:
        clean_line = line.rstrip('\n')
        last_names.append(string.capwords(clean_line.split(' ')[0]))
    pickle.dump(last_names, output)
    last_name_file.close()

    #Process Male First Names
    male_first_names = []
    male_first_name_file = open(os.path.join(data_dir, culture, "male-first-name.txt"),"rb")
    for line in male_first_name_file:
        clean_line = line.rstrip('\n')
        male_first_names.append(string.capwords(clean_line.split(' ')[0]))
    pickle.dump(male_first_names, output)
    male_first_name_file.close()

    #Process Female First Names
    female_first_names = []
    female_first_name_file = open(os.path.join(data_dir, culture, "female-first-name.txt"),"rb")
    for line in female_first_name_file:
        clean_line = line.rstrip('\n')
        female_first_names.append(string.capwords(clean_line.split(' ')[0]))
    pickle.dump(female_first_names, output)
    female_first_name_file.close()

    #Process the simple files
    for f in simple_files_to_process:
        temp = []
        if f == "email-domains.txt" or f == "latin-words.txt":
            sample_file = open(os.path.join(data_dir, f), "rb")
        else:
            sample_file = open(os.path.join(data_dir, culture, f), "rb")
        for line in sample_file:
            clean_line = line.rstrip('\n')
            temp.append(clean_line)
        pickle.dump(temp, output)
        sample_file.close()
        temp = []
    output.close()
开发者ID:cloudmaster,项目名称:barnum,代码行数:60,代码来源:convert_data.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python string.center函数代码示例发布时间:2022-05-27
下一篇:
Python string.capitalize函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap