Python string 模块,capwords() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用string.capwords()

项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def _remove_heist(self, ctx, *, target: str):
        """Remove a target from the heist list"""
        author = ctx.message.author
        settings = self.check_server_settings(author.server)
        if string.capwords(target) in settings["Targets"]:
            await self.bot.say("Are you sure you want to remove {} from the list of "
                               "targets?".format(string.capwords(target)))
            response = await self.bot.wait_for_message(timeout=15, author=author)
            if response is None:
                msg = "Canceling removal. You took too long."
            elif response.content.title() == "Yes":
                settings["Targets"].pop(string.capwords(target))
                self.save_system()
                msg = "{} was removed from the list of targets.".format(string.capwords(target))
            else:
                msg = "Canceling target removal."
        else:
            msg = "That target does not exist."
        await self.bot.say(msg)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def patch_2220(self, path):
        # Check if player data has the war game, and if not add it.
        if "Theme" not in path or not path["Theme"]:
            path["Theme"] = {"Jail": "jail", "OOB": "out on bail", "Police": "Police",
                             "Bail": "bail", "Crew": "crew", "Sentence": "sentence",
                             "Heist": "heist", "Vault": "vault"},
        if "Banks" in path:
            path["Targets"] = path.pop("Banks")
        if "Theme" not in path["Config"]:
            path["Config"]["Theme"] = "Heist"
        if "Crew Output" not in path["Config"]:
            path["Config"]["Crew Ouput"] = "None"
        if "Bail Cost" in path["Config"]:
            path["Config"].pop("Bail Cost")

        for target in path["Targets"]:
            path["Targets"][string.capwords(target)] = path["Targets"].pop(target)

        self.save_system()
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def jeopardy_start(self, ctx):
        if self.jeopardy_active:
            await self.bot.embed_reply(":no_entry: There's already a jeopardy game in progress")
            return
        self.jeopardy_active = True
        categories = []
        category_titles = []
        self.jeopardy_board_output = ""
        url = "http://jservice.io/api/random"
        for i in range(6):
            async with clients.aiohttp_session.get(url) as resp:
                data = await resp.json()
            categories.append(data[0]["category_id"])
        for category in categories:
            url = "http://jservice.io/api/category?id=" + str(category)
            async with clients.aiohttp_session.get(url) as resp:
                data = await resp.json()
            category_titles.append(string.capwords(data["title"]))
            self.jeopardy_board.append([category, False, False, False, False, False])
        self.jeopardy_max_width = max(len(category_title) for category_title in category_titles)
        for category_title in category_titles:
            self.jeopardy_board_output += category_title.ljust(self.jeopardy_max_width) + "  200 400 600 800 1000\n"
        await self.bot.embed_say(clients.code_block.format(self.jeopardy_board_output))
项目:alexafsm    作者:allenai    | 项目源码 | 文件源码
def _get_es_results(query: str, category: str, keyphrase: str, strict: bool) -> Response:
    skill_search = es_search
    if category:
        skill_search = skill_search.query('match',
                                          category=string.capwords(category)
                                          .replace(' And ', ' & ')
                                          .replace('Movies & Tv', 'Movies & TV'))
    if keyphrase:
        skill_search = skill_search.query('match', keyphrases=keyphrase)
    if query:
        operator = 'and' if strict else 'or'
        skill_search = skill_search.query('multi_match',
                                          query=query,
                                          fields=['name', 'description', 'usages', 'keyphrases'],
                                          minimum_should_match='50%',
                                          operator=operator) \
            .highlight('description', order='score', pre_tags=['*'], post_tags=['*']) \
            .highlight('title', order='score', pre_tags=['*'], post_tags=['*']) \
            .highlight('usages', order='score', pre_tags=['*'], post_tags=['*'])

    return skill_search.execute()
项目:nvidia-ml-py    作者:jonsafari    | 项目源码 | 文件源码
def _extractNVMLErrorsAsClasses():
    '''
    Generates a hierarchy of classes on top of NVMLError class.

    Each NVML Error gets a new NVMLError subclass. This way try,except blocks can filter appropriate
    exceptions more easily.

    NVMLError is a parent class. Each NVML_ERROR_* gets it's own subclass.
    e.g. NVML_ERROR_ALREADY_INITIALIZED will be turned into NVMLError_AlreadyInitialized
    '''
    this_module = sys.modules[__name__]
    nvmlErrorsNames = filter(lambda x: x.startswith("NVML_ERROR_"), dir(this_module))
    for err_name in nvmlErrorsNames:
        # e.g. Turn NVML_ERROR_ALREADY_INITIALIZED into NVMLError_AlreadyInitialized
        class_name = "NVMLError_" + string.capwords(err_name.replace("NVML_ERROR_", ""), "_").replace("_", "")
        err_val = getattr(this_module, err_name)
        def gen_new(val):
            def new(typ):
                obj = NVMLError.__new__(typ, val)
                return obj
            return new
        new_error_class = type(class_name, (NVMLError,), {'__new__': gen_new(err_val)})
        new_error_class.__module__ = __name__
        setattr(this_module, class_name, new_error_class)
        NVMLError._valClassMapping[err_val] = new_error_class
项目:goear-dl    作者:joanfont    | 项目源码 | 文件源码
def find_by_url(cls, song_url):
        soup = cls.__get_soup(song_url)

        og_title_tag = soup.find('meta', attrs={'property': cls.SONG_TITLE_META_OG_PROPERTY})
        og_title = og_title_tag.get('content')

        song_url_parts = song_url.split('/')
        song_id = song_url_parts[4]

        title, artist = og_title.split(' - ', 1)
        title = capwords(title)
        artist = capwords(artist)

        song_dict = {
            'song_id': song_id,
            'title': title,
            'artist': artist,
            'url': song_url
        }

        return Song(**song_dict)
项目:Leetcode    作者:staticor    | 项目源码 | 文件源码
def title_case(title, minor_words=''):
    if minor_words == '':
        return capwords(title)
    ignore_words = [w.lower() for w in minor_words.split()]
    res = ''; words= title.split()
    for i in range(len(words)):
        if i == 0:
            res += words[0].capitalize()
            res += ' '
        else:
            w = words[i]
            if w.lower() not in ignore_words:
                res += w.capitalize()
            else:
                res += w.lower()
            res += ' '
    return res.strip()
项目:nvidia-ml-py3    作者:nicolargo    | 项目源码 | 文件源码
def _extractNVMLErrorsAsClasses():
    '''
    Generates a hierarchy of classes on top of NVMLError class.

    Each NVML Error gets a new NVMLError subclass. This way try,except blocks can filter appropriate
    exceptions more easily.

    NVMLError is a parent class. Each NVML_ERROR_* gets it's own subclass.
    e.g. NVML_ERROR_ALREADY_INITIALIZED will be turned into NVMLError_AlreadyInitialized
    '''
    this_module = sys.modules[__name__]
    nvmlErrorsNames = filter(lambda x: x.startswith("NVML_ERROR_"), dir(this_module))
    for err_name in nvmlErrorsNames:
        # e.g. Turn NVML_ERROR_ALREADY_INITIALIZED into NVMLError_AlreadyInitialized
        class_name = "NVMLError_" + string.capwords(err_name.replace("NVML_ERROR_", ""), "_").replace("_", "")
        err_val = getattr(this_module, err_name)
        def gen_new(val):
            def new(typ):
                obj = NVMLError.__new__(typ, val)
                return obj
            return new
        new_error_class = type(class_name, (NVMLError,), {'__new__': gen_new(err_val)})
        new_error_class.__module__ = __name__
        setattr(this_module, class_name, new_error_class)
        NVMLError._valClassMapping[err_val] = new_error_class
项目:Colony    作者:DeflatedPickle    | 项目源码 | 文件源码
def add_relation(self, colonist):
        menu = tk.Menu(self)

        for relationship_type in colonist.relationships:
            if isinstance(colonist.relationships[relationship_type], dict):
                menu_relations = tk.Menu(menu)

                for relationship in colonist.relationships[relationship_type]:
                    if isinstance(colonist.relationships[relationship_type][relationship], list):
                        menu_sibling = tk.Menu(menu_relations)

                        for sibling in colonist.relationships[relationship_type][relationship]:
                            menu_sibling.add_command(label=capwords(sibling.get_name()))

                        if colonist.relationships[relationship_type][relationship]:
                            menu_relations.add_cascade(label=capwords(relationship), menu=menu_sibling)

                    else:
                        if colonist.relationships[relationship_type][relationship]:
                            menu_relations.add_command(label=capwords(relationship))

                menu.add_cascade(label=capwords(relationship_type), menu=menu_relations)

        self.add_cascade(label=colonist.get_name(), menu=menu)
项目:griffith    作者:Strit    | 项目源码 | 文件源码
def get_searches(self):
        # Try to find both id and film title for each search result
        elements = string.split(self.page, "<li>")
        self.number_results = elements[-1]

        if (elements[0] != ''):
            for element in elements:
                id = gutils.trim(element, "?codice=", "\">")
                if id <> '':
                    self.ids.append(id)
                    title = self.capwords(gutils.convert_entities(gutils.trim(element, "<b>", "</b>")))
                    year = re.search('([[][0-9]{4}[]])', element)
                    if year:
                        year = year.group(0)
                    if year:
                        self.titles.append(title + ' ' + year)
                    else:
                        self.titles.append(title)
        else:
            self.number_results = 0


#
# Plugin Test
#
项目:codewars_python    作者:staticor    | 项目源码 | 文件源码
def title_case(title, minor_words=''):
    if minor_words == '':
        return capwords(title)
    ignore_words = [w.lower() for w in minor_words.split()]
    res = ''; words= title.split()
    for i in range(len(words)):
        if i == 0:
            res += words[0].capitalize()
            res += ' '
        else:
            w = words[i]
            if w.lower() not in ignore_words:
                res += w.capitalize()
            else:
                res += w.lower()
            res += ' '
    return res.strip()
项目:BigBrotherBot-For-UrT43    作者:ptitbigorneau    | 项目源码 | 文件源码
def parseLine(self, line):
        """
        Parse a log line creating necessary events.
        :param line: The log line to be parsed
        """
        m = self.getLineParts(line)
        if not m:
            return False

        match, action, data, client, target = m
        func = 'On%s' % string.capwords(action).replace(' ', '')

        if hasattr(self, func):
            func = getattr(self, func)
            event = func(action, data, match)
            if event:
                self.queueEvent(event)
        elif action in self._eventMap:
            self.queueEvent(self.getEvent(self._eventMap[action], data=data, client=client, target=target))

        else:
            data = str(action) + ': ' + str(data)
            self.queueEvent(self.getEvent('EVT_UNKNOWN', data=data, client=client, target=target))
项目:BigBrotherBot-For-UrT43    作者:ptitbigorneau    | 项目源码 | 文件源码
def parse_line(self, line):
        """
        Parse a log line creating necessary events.
        :param line: The log line to be parsed
        """
        m = self.getLineParts(line)
        if not m:
            return False

        match, action, data, client, target = m
        func = 'On%s' % string.capwords(action).replace(' ','')

        if hasattr(self, func):
            func = getattr(self, func)
            event = func(action, data, match)
            if event:
                self.queueEvent(event)
        elif action in self._eventMap:
            self.queueEvent(self.getEvent(self._eventMap[action], data=data, client=client, target=target))
        elif action in self._actionMap:
            # addition for cod5 actionMapping
            self.translateAction(action, data, match)
        else:
            self.queueEvent(self.getEvent('EVT_UNKNOWN', str(action) + ': ' + str(data), client, target))
项目:py3nvml    作者:fbcotter    | 项目源码 | 文件源码
def _extractNVMLErrorsAsClasses():
    '''
    Generates a hierarchy of classes on top of NVMLError class.

    Each NVML Error gets a new NVMLError subclass. This way try,except blocks can filter appropriate
    exceptions more easily.

    NVMLError is a parent class. Each NVML_ERROR_* gets it's own subclass.
    e.g. NVML_ERROR_ALREADY_INITIALIZED will be turned into NVMLError_AlreadyInitialized
    '''
    this_module = sys.modules[__name__]
    nvmlErrorsNames = [x for x in dir(this_module) if x.startswith("NVML_ERROR_")]
    for err_name in nvmlErrorsNames:
        # e.g. Turn NVML_ERROR_ALREADY_INITIALIZED into NVMLError_AlreadyInitialized
        class_name = "NVMLError_" + string.capwords(err_name.replace("NVML_ERROR_", ""), "_").replace("_", "")
        err_val = getattr(this_module, err_name)
        def gen_new(val):
            def new(typ):
                obj = NVMLError.__new__(typ, val)
                return obj
            return new
        new_error_class = type(class_name, (NVMLError,), {'__new__': gen_new(err_val)})
        new_error_class.__module__ = __name__
        setattr(this_module, class_name, new_error_class)
        NVMLError._valClassMapping[err_val] = new_error_class
项目:sharead    作者:strin    | 项目源码 | 文件源码
def extract_metadata_from_pdf(data):
    stream = StringIO(data)
    # get access token using refresh token.
    resp = requests.post('https://api.mendeley.com/oauth/token',
                              data=('grant_type=refresh_token&refresh_token=%s'
                                    '&redirect_uri=%s'
                                    % (REFRESH_TOKEN, REDIRECT_URI)),
                              headers={
                                  'Content-Type': 'application/x-www-form-urlencoded'
                              },
                              auth=HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)
                        ).json()
    access_token = resp['access_token']
    # assert(resp['refresh_token'] == REFRESH_TOKEN)
    # use access token to request paper metadata.
    result = requests.post('https://api.mendeley.com/documents',
                            data=stream.read(),
                            headers={
                                'Authorization': 'Bearer %s' % access_token,
                                'Content-Type': 'application/pdf',
                                'Content-Disposition': 'attachment; filename="example.pdf"'
                            }).json()
    result['title'] = string.capwords(result['title']) # convert to same title format.
    return result
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def cmdln():
    """Setup command line parser.
    """
    cmdln = optparse.OptionParser(usage=USAGE, description=DESCR)
    cmdln.add_option('-r', dest='recurse', action='store_true',
                     help='Recurse into subdirs')
    cmdln.add_option('-s', dest='silent', action='store_true',
                     help='Silent mode')
    cmdln.add_option('-n', dest='dryrun', action='store_true',
                     help='dry run/No-op mode (don\'t actually rename)')
    cmdln.add_option('-L', dest='lower', action='store_true',
                     help='make Lower case (string.lower)')
    cmdln.add_option('-U', dest='upper', action='store_true',
                     help='make Upper case (string.upper)')
    cmdln.add_option('-C', dest='capwords', action='store_true',
                     help='Capitalize words (string.capwords)')
    cmdln.add_option('-f', dest='fromchars', default='',
                     help='translate From FROMCHARS characters (requires -t)')
    cmdln.add_option('-t', dest='tochars', default='',
                     help='translate To TOCHARS characters (requires -f)')
    cmdln.add_option('-d', dest='delchars', default='',
                     help='Delete DELCHARS characters from file names')
    cmdln.add_option('-l', dest='limitglob', default='*',
                     help='Limit file globbing to LIMITGLOB pattern')
    opts, args = cmdln.parse_args(sys.argv[1:])
    opts.stringfunc = lambda x: x
    if opts.capwords: opts.stringfunc = string.capwords
    if opts.upper:    opts.stringfunc = string.upper
    if opts.lower:    opts.stringfunc = string.lower
    error_checks(cmdln, args, opts)
    return opts, args[0]
项目:PYKE    作者:muddyfish    | 项目源码 | 文件源码
def func(self, x: Node.dict_indexable):
        """0 - len (floor(log(x)) with numbers)
1 - lower
2 - upper
3 - swapcase
4 - title
5 - capitalize
6 - capwords
7 - strip
8 - lstrip
9 - rstrip"""
        if self.config == 0:
            return self.len(x)
        return Letters.settings[self.config-1](x)
项目:CorpBot.py    作者:corpnewt    | 项目源码 | 文件源码
def define(self, ctx, *, word : str):
        """Gives the definition of the word passed."""

        # Check if we're suppressing @here and @everyone mentions
        if self.settings.getServerStat(ctx.message.server, "SuppressMentions").lower() == "yes":
            suppress = True
        else:
            suppress = False

        if not word:
            msg = 'Usage: `{}define [word]`'.format(ctx.prefix)
            await self.bot.send_message(ctx.message.channel, msg)
            return
        url = "http://api.urbandictionary.com/v0/define?term={}".format(quote(word))
        msg = 'I couldn\'t find a definition for "{}"...'.format(word) 
        r = requests.get(url, headers = {'User-agent': self.ua})
        theJSON = r.json()["list"]
        if len(theJSON):
            # Got it - let's build our response
            ourWord = theJSON[0]
            msg = '__**{}:**__\n\n{}'.format(string.capwords(ourWord["word"]), ourWord["definition"])
            if ourWord["example"]:
                msg = '{}\n\n__Example(s):__\n\n*{}*'.format(msg, ourWord["example"])

        # await self.bot.send_message(ctx.message.channel, msg)
        # Check for suppress
        if suppress:
            msg = Nullify.clean(msg)
        await Message.say(self.bot, msg, ctx.message.channel, ctx.message.author)
项目:CorpBot.py    作者:corpnewt    | 项目源码 | 文件源码
def randefine(self, ctx):
        """Gives a random word and its definition."""
        url = "http://api.urbandictionary.com/v0/random"
        r = requests.get(url, headers = {'User-agent': self.ua})
        theJSON = r.json()["list"]
        if len(theJSON):
            # Got it - let's build our response
            ourWord = theJSON[0]
            msg = '__**{}:**__\n\n{}'.format(string.capwords(ourWord["word"]), ourWord["definition"])
            if ourWord["example"]:
                msg = '{}\n\n__Example(s):__\n\n*{}*'.format(msg, ourWord["example"])

        # await self.bot.send_message(ctx.message.channel, msg)
        await Message.say(self.bot, msg, ctx.message.channel, ctx.message.author)
项目:gns3-documentation-template    作者:GNS3    | 项目源码 | 文件源码
def _callback_document_authors(self, request_id, results, exception):
        if exception:
            raise exception

        file_id = self._document_items[request_id]
        authors = set()
        items = results.get('revisions', [])
        if items:
            for item in items:
                authors.add(string.capwords(item['lastModifyingUser']['displayName']))
        authors = list(authors)
        authors.sort()
        self._documents[file_id].authors = authors
        item = self._documents[file_id]
        self._write_to_cache(file_id + '_authors', self._documents[file_id].modifiedTime, authors)
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
def addHeader (self,key,value):
        k=string.capwords(key,"-")
        if k!="Accept-Encoding":
            self.__headers[k]=value
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
def __getitem__ (self,key):
        k=string.capwords(key,"-")
        if self.__headers.has_key(k):
            return self.__headers[k]
        else:
            return ""
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
def addHeader (self,key,value):
        k=string.capwords(key,"-")
        if k!="Transfer-Encoding":
            self.__headers+=[(k,value)]
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
def addHeader (self,key,value):
        k=string.capwords(key,"-")
        if k!="Accept-Encoding":
            self.__headers[k]=value
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
def __getitem__ (self,key):
        k=string.capwords(key,"-")
        if self.__headers.has_key(k):
            return self.__headers[k]
        else:
            return ""
项目:loving-ai    作者:opencog    | 项目源码 | 文件源码
def _processFormal(self, elem, sessionID):
        """Process a <formal> AIML element.

        <formal> elements process their contents recursively, and then
        capitalize the first letter of each word of the result.

        """
        response = ""
        for e in elem[2:]:
            response += self._processElement(e, sessionID)
        return string.capwords(response)

    # <gender>
项目:loving-ai    作者:opencog    | 项目源码 | 文件源码
def __setitem__(self, 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
项目:isthislegit    作者:duo-labs    | 项目源码 | 文件源码
def normalize(header):
    return string.capwords(header.lower(), '-')
项目:deckhand    作者:att-comdev    | 项目源码 | 文件源码
def to_camel_case(s):
    """Convert string to camel case."""
    return (s[0].lower() + string.capwords(s, sep='_')
            .replace('_', '')[1:] if s else s)
项目:core    作者:IntelligentTrading    | 项目源码 | 文件源码
def cap_first_word(arg):
  if type(arg) == str:
    s = arg.strip()
    return s[0].upper() + s[1:None]

  if type(arg) == list:
    return [string.capwords(arg[0])] + arg[1:None]

  raise TypeError("Invalid type passed to function: " + type(arg))
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def draw(self, context):
        layout = self.layout
        layout.label(self.bl_label)
        for op, name in self.operators:
            text = capwords(name.replace("_", " ")) + " (Meta-Rig)"
            layout.operator(op, icon='OUTLINER_OB_ARMATURE', text=text)
项目:goear-dl    作者:joanfont    | 项目源码 | 文件源码
def __get_song_from_list(cls, element):
        ul = element.find('ul', {'class': cls.BOARD_CONTENT_CLASS})

        url = ul.get(cls.SONG_URL_PROP)

        id_parts = url.split('/')
        song_id = id_parts[4] if len(id_parts) > 4 else None

        title_item = ul.find('li', {'class': cls.SONG_TITLE_CLASS})
        title = capwords(title_item.text) if title_item else None

        artist_item = ul.find('li', {'class': cls.SONG_ARTIST_CLASS})
        artist = capwords(artist_item.text) if artist_item else None

        bit_rate = ul.find('li', {'class': cls.SONG_BIT_RATE_CLASS}).text
        bit_rate_parts = bit_rate.split()
        bit_rate = bit_rate_parts[0] if bit_rate_parts else None

        length = ul.find('li', {'class': cls.SONG_LENGTH_CLASS}).text
        length = Song.get_length_from_string(length)

        song_dict = {
            'song_id': song_id,
            'title': title,
            'artist': artist,
            'bit_rate': bit_rate,
            'length': length,
            'url': url
        }

        return Song(**song_dict)
项目:defcon-workshop    作者:devsecops    | 项目源码 | 文件源码
def addHeader (self,key,value):
        k=string.capwords(key,"-")
        if k.lower() not in ["accept-encoding","content-length","if-modified-since","if-none-match"]:
            self._headers[k]=value
项目:defcon-workshop    作者:devsecops    | 项目源码 | 文件源码
def delHeader (self,key):
        k = string.capwords(key,"-")
        if self._headers.has_key(k):
        del self._headers[k]
项目:defcon-workshop    作者:devsecops    | 项目源码 | 文件源码
def __getitem__ (self,key):
        k=string.capwords(key,"-")
        if k in self._headers:
            return self._headers[k]
        else:
            return ""
项目:defcon-workshop    作者:devsecops    | 项目源码 | 文件源码
def addHeader (self,key,value):
        k=string.capwords(key,"-")
        self._headers+=[(k,value)]
项目:cuny-bdif    作者:aristotle-tek    | 项目源码 | 文件源码
def method_for(self, name):
        """Return the MWS API method referred to in the argument.
           The named method can be in CamelCase or underlined_lower_case.
           This is the complement to MWSConnection.any_call.action
        """
        action = '_' in name and string.capwords(name, '_') or name
        if action in api_call_map:
            return getattr(self, api_call_map[action])
        return None
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_capwords(self):
        self.assertEqual(string.capwords('abc def ghi'), 'Abc Def Ghi')
        self.assertEqual(string.capwords('abc\tdef\nghi'), 'Abc Def Ghi')
        self.assertEqual(string.capwords('abc\t   def  \nghi'), 'Abc Def Ghi')
        self.assertEqual(string.capwords('ABC DEF GHI'), 'Abc Def Ghi')
        self.assertEqual(string.capwords('ABC-DEF-GHI', '-'), 'Abc-Def-Ghi')
        self.assertEqual(string.capwords('ABC-def DEF-ghi GHI'), 'Abc-def Def-ghi Ghi')
        self.assertEqual(string.capwords('   aBc  DeF   '), 'Abc Def')
        self.assertEqual(string.capwords('\taBc\tDeF\t'), 'Abc Def')
        self.assertEqual(string.capwords('\taBc\tDeF\t', '\t'), '\tAbc\tDef\t')
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test():
    string.capwords(1)
项目:Red_Star    作者:medeor413    | 项目源码 | 文件源码
def _inforole(self, msg):
        """
        provides an infodump of a role, including permissions and position
        """
        try:
            args = shlex.split(msg.content)
        except ValueError as e:
            self.logger.warning("Unable to split {data.content}. {e}")
            raise CommandSyntaxError(e)
        if len(args) > 1:
            name = capwords(args[1])
            role = find_role(msg.guild, args[1])
            if role:
                t_dict = {
                    "name": role.name,
                    "permissions": role.permissions,
                    "colour": role.colour,
                    "hoist": role.hoist,
                    "mentionable": role.mentionable,
                    "position": role.position,
                    "created_at": role.created_at,
                    "id": role.id
                }
                t_string = ""
                for k, v in t_dict.items():
                    if k != "permissions":
                        t_string = f"{t_string}{k}: {v!s}\n"
                    else:
                        t_string += k + ": " + ", ".join({x.upper() for x, y in v if y}) + "\n"
                await respond(msg, f"**ANALYSIS: role {role.name} has parameters :**\n ```{t_string}```")
            else:
                await respond(msg, f"**NEGATIVE. ANALYSIS: no role {name} found.**")
        else:
            raise CommandSyntaxError
项目:Red_Star    作者:medeor413    | 项目源码 | 文件源码
def _help(self, msg):
        if not self.categories:
            await self.build_help()
        try:
            search = msg.clean_content.split(" ")[1].lower()
        except IndexError:
            cates = "\n".join(sorted([capwords(x, "_") for x in self.categories.keys()]))
            await respond(msg, f"**ANALYSIS: Command categories:**```\n{cates}\n```")
            return
        if search in [x.lower() for x in self.commands.keys()]:
            cmd = self.commands[search]
            name = cmd.name
            syn = cmd.syntax
            if not syn:
                syn = "N/A"
            doc = cmd.__doc__
            perms = cmd.perms
            cate = capwords(cmd.category, "_")
            aliases = f"(Aliases: {', '.join(cmd.aliases)})" if cmd.aliases else ""
            if not {x for x, y in msg.author.guild_permissions if y} >= perms:
                raise UserPermissionError
            text = f"**ANALYSIS: Command {name}:**```\n{name} (Category {cate}) {aliases}\n\n{doc}\n\n" \
                   f"Syntax: {syn}\n```"
            await respond(msg, text)
        elif search in self.categories.keys():
            name = capwords(search, "_")
            userperms = {x for x, y in msg.author.guild_permissions if y}
            cmds = {x.name for x in self.categories[search].values() if userperms >= x.perms}
            cmds = sorted(list(cmds))
            if cmds:
                text = "\n".join(cmds)
                await respond(msg, f"**ANALYSIS: Category {name}:**```\n{text}\n```")
            else:
                await respond(msg, "**WARNING: You do not have permission for any command in this category.**")
        else:
            await respond(msg, f"**WARNING: No such category or command {search}**")
项目:tellmeabout.coffee    作者:billyfung    | 项目源码 | 文件源码
def country_from_name(name):
    countrydict = COUNTRY_DICT
    is_country_in_here = [x for x in countrydict.keys() if x in name.lower()]
    country = ''
    if is_country_in_here:
        country = string.capwords(is_country_in_here[0])
    return country
项目:spqrel_tools    作者:LCAS    | 项目源码 | 文件源码
def _processFormal(self, elem, sessionID):
        """Process a <formal> AIML element.

        <formal> elements process their contents recursively, and then
        capitalize the first letter of each word of the result.

        """
        response = ""
        for e in elem[2:]:
            response += self._processElement(e, sessionID)
        return string.capwords(response)

    # <gender>
项目:spqrel_tools    作者:LCAS    | 项目源码 | 文件源码
def __setitem__(self, 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
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_capwords(self):
        self.assertEqual(string.capwords('abc def ghi'), 'Abc Def Ghi')
        self.assertEqual(string.capwords('abc\tdef\nghi'), 'Abc Def Ghi')
        self.assertEqual(string.capwords('abc\t   def  \nghi'), 'Abc Def Ghi')
        self.assertEqual(string.capwords('ABC DEF GHI'), 'Abc Def Ghi')
        self.assertEqual(string.capwords('ABC-DEF-GHI', '-'), 'Abc-Def-Ghi')
        self.assertEqual(string.capwords('ABC-def DEF-ghi GHI'), 'Abc-def Def-ghi Ghi')
        self.assertEqual(string.capwords('   aBc  DeF   '), 'Abc Def')
        self.assertEqual(string.capwords('\taBc\tDeF\t'), 'Abc Def')
        self.assertEqual(string.capwords('\taBc\tDeF\t', '\t'), '\tAbc\tDef\t')
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_capwords(self):
        self.assertEqual(string.capwords('abc def ghi'), 'Abc Def Ghi')
        self.assertEqual(string.capwords('abc\tdef\nghi'), 'Abc Def Ghi')
        self.assertEqual(string.capwords('abc\t   def  \nghi'), 'Abc Def Ghi')
        self.assertEqual(string.capwords('ABC DEF GHI'), 'Abc Def Ghi')
        self.assertEqual(string.capwords('ABC-DEF-GHI', '-'), 'Abc-Def-Ghi')
        self.assertEqual(string.capwords('ABC-def DEF-ghi GHI'), 'Abc-def Def-ghi Ghi')
        self.assertEqual(string.capwords('   aBc  DeF   '), 'Abc Def')
        self.assertEqual(string.capwords('\taBc\tDeF\t'), 'Abc Def')
        self.assertEqual(string.capwords('\taBc\tDeF\t', '\t'), '\tAbc\tDef\t')
项目:ppytrading    作者:yusukemurayama    | 项目源码 | 文件源码
def _show_classes(self, rule_type):
        """????rule_type?????????????"""
        import string
        plogger.info(os.linesep + '# {}?findkey??'.format(string.capwords(rule_type)))
        for findkey in sorted(SimpleFinder.getinstance().find_class_all(rule_type).keys()):
            plogger.info('- ' + findkey)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_capwords(self):
        self.assertEqual(string.capwords('abc def ghi'), 'Abc Def Ghi')
        self.assertEqual(string.capwords('abc\tdef\nghi'), 'Abc Def Ghi')
        self.assertEqual(string.capwords('abc\t   def  \nghi'), 'Abc Def Ghi')
        self.assertEqual(string.capwords('ABC DEF GHI'), 'Abc Def Ghi')
        self.assertEqual(string.capwords('ABC-DEF-GHI', '-'), 'Abc-Def-Ghi')
        self.assertEqual(string.capwords('ABC-def DEF-ghi GHI'), 'Abc-def Def-ghi Ghi')
        self.assertEqual(string.capwords('   aBc  DeF   '), 'Abc Def')
        self.assertEqual(string.capwords('\taBc\tDeF\t'), 'Abc Def')
        self.assertEqual(string.capwords('\taBc\tDeF\t', '\t'), '\tAbc\tDef\t')
项目:aiml3    作者:Decalogue    | 项目源码 | 文件源码
def _processFormal(self, elem, sessionID):
        """Process a <formal> AIML element.

        <formal> elements process their contents recursively, and then
        capitalize the first letter of each word of the result.

        """                
        response = ""
        for e in elem[2:]:
            response += self._processElement(e, sessionID)
        return string.capwords(response)

    # <gender>
项目:aiml3    作者:Decalogue    | 项目源码 | 文件源码
def __setitem__(self, i, y):
        self._regexIsDirty = True
        # for each entry the user adds, we actually add three entrys:
        super(type(self),self).__setitem__(i.lower(),y.lower()) # key = value
        super(type(self),self).__setitem__(string.capwords(i), string.capwords(y)) # Key = Value
        super(type(self),self).__setitem__(i.upper(), y.upper()) # KEY = VALUE