python 中的 title() 方法在没有像这样的词时编写函数

问题描述 投票:0回答:3

使用功能

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

试用

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
python methods title
3个回答
0
投票

这应该有效:

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

它手动按空格(而不是任何其他字符)拆分单词,然后将每个标记的第一个字母大写。它通过将第一个字母分开,大写,然后连接单词的其余部分来做到这一点。如果单词只有一个字母长,我使用三元

if
语句来避免
IndexError


0
投票

使用字符串库中的

.capwords()

import string

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

演示https://repl.it/repls/BlankMysteriousMenus


-1
投票

这是我对如何使用 NLP 将任何文本转换为标题格式的最新答案。

首先,安装Spacy模型包。

pip install spacy

然后,安装英文核心模型。

python -m spacy download en_core_web_sm

最后,使用这个简单的脚本将任何文本转换为标题格式。

from string import capwords

import spacy

nlp = spacy.load("en_core_web_sm")
text = "Natural language processing with python's NLTK package"
title = ''
stop_words = ['ADP', 'CONJ', 'CCONJ', 'DET']
for word in text.split():
    if word.islower():
        nlp_word = nlp(word)
        if nlp_word[0].pos_ in stop_words:
            title += word + ' '
        else:
            title += capwords(word) + ' '
    else:
        title += word + ' '
print(title)  # Natural Language Processing with Python's NLTK Package
© www.soinside.com 2019 - 2024. All rights reserved.