title() method in python writing functions when word like aren't
Asked Answered
B

3

-1

using function

def make_cap(sentence):
    return sentence.title()

tryining out

make_cap("hello world")
'Hello World'


# it workd but when I have world like "aren't" and 'isn't". how to write function for that


a = "I haven't worked hard"
make_cap(a) 
"This Isn'T A Right Thing"  # it's wrong I am aware of \ for isn\'t but confused how to include it in function
Barefoot answered 22/7, 2019 at 14:40 Comment(1)
What is the desired capitalisation? "I Haven't Worked Hard"? "I haven't Worked hard"?Pyrrha
B
0

This should work:

def make_cap(sentence):
    return " ".join(word[0].title() + (word[1:] if len(word) > 1 else "") for word in sentence.split(" "))

It manually splits the word by spaces (and not by any other character), and then capitalizes the first letter of each token. It does this by separating that first letter out, capitalizing it, and then concatenating the rest of the word. I used a ternary if statement to avoid an IndexError if the word is only one letter long.

Burck answered 22/7, 2019 at 14:47 Comment(0)
J
0

Use .capwords() from the string library.

import string

def make_cap(sentence):
    return string.capwords(sentence)

Demo: https://repl.it/repls/BlankMysteriousMenus

Jocelyn answered 22/7, 2019 at 14:49 Comment(0)
V
0

Here's my updated answer to how to convert any text to title format using NLP.

First, install the Spacy model package.

pip install spacy

Then, install the English core model.

python -m spacy download en_core_web_sm

Finally, convert any text to title format with this simple script.

import spacy
from string import capwords

nlp = spacy.load('en_core_web_sm')
title = "Natural language processing with python's NLTK package."
stop_words = ['ADP', 'CONJ', 'CCONJ', 'DET', 'PART']
doc = nlp(title)
for word in doc:
    w = word.text
    if w.islower():
        if word.pos_ not in stop_words:
            title = title.replace(w, capwords(w), 1)

print(title)  # Natural Language Processing with Python's NLTK Package.
Vernellvernen answered 25/12, 2022 at 9:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.