Python string.capwords() Examples

The following are 30 code examples of string.capwords(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module string , or try the search function .
Example #1
Source File: test_extractor.py    From gallery-dl with GNU General Public License v2.0 7 votes vote down vote up
def test_names(self):
        """Ensure extractor classes are named CategorySubcategoryExtractor"""
        def capitalize(c):
            if "-" in c:
                return string.capwords(c.replace("-", " ")).replace(" ", "")
            return c.capitalize()

        for extr in extractor.extractors():
            if extr.category not in ("", "oauth"):
                expected = "{}{}Extractor".format(
                    capitalize(extr.category),
                    capitalize(extr.subcategory),
                )
                if expected[0].isdigit():
                    expected = "_" + expected
                self.assertEqual(expected, extr.__name__) 
Example #2
Source File: pynvml.py    From satori with Apache License 2.0 6 votes vote down vote up
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 
Example #3
Source File: clients.py    From alexafsm with Apache License 2.0 6 votes vote down vote up
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() 
Example #4
Source File: pynvml.py    From MoePhoto with Apache License 2.0 6 votes vote down vote up
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 
Example #5
Source File: pynvml.py    From nvidia-ml-py with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #6
Source File: heist.py    From discord_cogs with GNU General Public License v3.0 6 votes vote down vote up
def _remove_heist(self, ctx, *, target: str):
        """Remove a target from the heist list"""
        author = ctx.message.author
        guild = ctx.guild
        targets = await self.thief.get_guild_targets(guild)
        if string.capwords(target) in targets:
            await ctx.send("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, check=lambda x: x.author == author)
            if response is None:
                msg = "Canceling removal. You took too long."
            elif response.content.title() == "Yes":
                targets.pop(string.capwords(target))
                await self.thief.save_targets(guild, targets)
                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 ctx.send(msg) 
Example #7
Source File: test_string.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
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') 
Example #8
Source File: pynvml.py    From trains with Apache License 2.0 5 votes vote down vote up
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 
Example #9
Source File: server.py    From python-for-IBM-i-examples with MIT License 5 votes vote down vote up
def titleize(column):
    title = column.replace('_', ' ')
    return capwords(title) 
Example #10
Source File: reqresp.py    From darkc0de-old-stuff with GNU General Public License v3.0 5 votes vote down vote up
def __getitem__ (self,key):
		k=string.capwords(key,"-")
		if self.__headers.has_key(k):
			return self.__headers[k]
		else:
			return "" 
Example #11
Source File: reqresp.py    From darkc0de-old-stuff with GNU General Public License v3.0 5 votes vote down vote up
def addHeader (self,key,value):
		k=string.capwords(key,"-")
		if k!="Transfer-Encoding":
			self.__headers+=[(k,value)] 
Example #12
Source File: plugin_wrapper.py    From deepdiy with MIT License 5 votes vote down vote up
def __init__(self,package_name):
		super(PluginWrapper, self).__init__()
		self.package_name=package_name
		self.type=package_name.split('.')[1]
		self.id=package_name.split('.')[2]
		self.title=string.capwords(self.id.replace('_',' '))
		self.import_package()
		self.instantiate() 
Example #13
Source File: hitomi.py    From gallery-dl with GNU General Public License v2.0 5 votes vote down vote up
def _data_from_gallery_page(self, info):
        url = "{}/galleries/{}.html".format(self.root, info["id"])

        # follow redirects
        while True:
            response = self.request(url, fatal=False)
            if b"<title>Redirect</title>" not in response.content:
                break
            url = text.extract(response.text, "href='", "'")[0]
            if not url.startswith("http"):
                url = text.urljoin(self.root, url)

        if response.status_code >= 400:
            return {}

        def prep(value):
            return [
                text.unescape(string.capwords(v))
                for v in text.extract_iter(value or "", '.html">', '<')
            ]

        extr = text.extract_from(response.text)
        return {
            "artist"    : prep(extr('<h2>', '</h2>')),
            "group"     : prep(extr('<td>Group</td><td>', '</td>')),
            "parody"    : prep(extr('<td>Series</td><td>', '</td>')),
            "characters": prep(extr('<td>Characters</td><td>', '</td>')),
        } 
Example #14
Source File: hitomi.py    From gallery-dl with GNU General Public License v2.0 5 votes vote down vote up
def _data_from_gallery_info(self, info):
        language = info.get("language")
        if language:
            language = language.capitalize()

        date = info.get("date")
        if date:
            date += ":00"

        tags = []
        for tinfo in info.get("tags") or ():
            tag = string.capwords(tinfo["tag"])
            if tinfo.get("female"):
                tag += " ♀"
            elif tinfo.get("male"):
                tag += " ♂"
            tags.append(tag)

        return {
            "gallery_id": text.parse_int(info["id"]),
            "title"     : info["title"],
            "type"      : info["type"].capitalize(),
            "language"  : language,
            "lang"      : util.language_to_code(language),
            "date"      : text.parse_datetime(date, "%Y-%m-%d %H:%M:%S%z"),
            "tags"      : tags,
        } 
Example #15
Source File: test_string.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
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') 
Example #16
Source File: Request.py    From wfuzz with GNU General Public License v2.0 5 votes vote down vote up
def delHeader(self, key):
        k = string.capwords(key, "-")
        if k in self._headers:
            del self._headers[k] 
Example #17
Source File: Request.py    From wfuzz with GNU General Public License v2.0 5 votes vote down vote up
def addHeader(self, key, value):
        k = string.capwords(key, "-")
        self._headers[k] = value 
Example #18
Source File: Response.py    From wfuzz with GNU General Public License v2.0 5 votes vote down vote up
def addHeader(self, key, value):
        k = string.capwords(key, "-")
        self._headers += [(k, value)] 
Example #19
Source File: connection.py    From aws-extender with MIT License 5 votes vote down vote up
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 
Example #20
Source File: helper.py    From pyepw with Apache License 2.0 5 votes vote down vote up
def normalize_object_name(internal_name):
    name = internal_name.replace('/', ' or ').strip()
    name = string.capwords(name)
    name = name.replace(' ', '')
    return name 
Example #21
Source File: agent.py    From cvpysdk with Apache License 2.0 5 votes vote down vote up
def __repr__(self):
        """String representation of the instance of this class."""
        representation_string = '"{0}" Agent instance for Client: "{1}"'

        return representation_string.format(
            string.capwords(self.agent_name), self._client_object.client_name
        ) 
Example #22
Source File: ke_create_posts.py    From yournextrepresentative with GNU Affero General Public License v3.0 5 votes vote down vote up
def areas_from_csv(self, csv_filename, code_column, name_column, county_id_restriction):
        # At this point we have the election, organisation and area types ready.
        # Iterate over the senators CSV to build our lists of other things to add.

        areas = {}

        reader = csv.DictReader(open('elections/kenya/data/' + csv_filename))
        for row in reader:

            if (county_id_restriction is not None) and county_id_restriction != row.get('County Code'):
                continue

            # In this script we only care about the areas, because we're building the posts
            # Actual candidates (and their parties) are done elsewhere

            area_id = row[code_column]

            # Do we already have this area?
            if area_id not in areas:

                # This is a dict rather than just a name in case we need to easily add anything in future.
                areas[area_id] = {
                    'id': area_id,
                    'name': string.capwords(row[name_column])
                }

        return areas 
Example #23
Source File: sensor.py    From esxi_stats with MIT License 5 votes vote down vote up
def measureFormat(input):
    """Return measurement in readable form."""
    if input in MAP_TO_MEASUREMENT.keys():
        return MAP_TO_MEASUREMENT[input]
    else:
        return capwords(input.replace("_", " ")) 
Example #24
Source File: pynvml.py    From trains-agent with Apache License 2.0 5 votes vote down vote up
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 
Example #25
Source File: recipe-578090.py    From code with MIT License 5 votes vote down vote up
def do_capwords(self, string):
        return capwords(string) 
Example #26
Source File: test_string.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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') 
Example #27
Source File: QuestTaskDNA.py    From Pirates-Online-Rewritten with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getProgressMessage(self, taskState):
        QuestTaskDNA.getProgressMessage(self, taskState)
        itemName = PLocalizer.QuestItemNames[self.itemId][0]
        progressMsg = PLocalizer.DefeatAroundPropProgress % string.capwords(itemName)
        return (
         progressMsg, PiratesGuiGlobals.TextFG10) 
Example #28
Source File: gen_data.py    From barnum-proj with GNU General Public License v2.0 5 votes vote down vote up
def create_street():
    number = random.randint(1, 9999)
    name = string.capwords(random.choice(street_names))
    street_type = string.capwords(random.choice(street_types))
    return("%s %s %s" % (number, name, street_type)) 
Example #29
Source File: test_string.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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') 
Example #30
Source File: generic_utils.py    From BAMnet with Apache License 2.0 5 votes vote down vote up
def get_embeddings(self, word):
        word_list = [word, word.upper(), word.lower(), word.title(), string.capwords(word, '_')]

        for w in word_list:
            try:
                return self.model[w]
            except KeyError:
                # print('Can not get embedding for ', w)
                continue
        return None