仅限Python 3中字符串中的某些单词

时间:2018-03-29 11:06:11

标签: python-3.x capitalize

您好我正在尝试创建一个功能,使一个短语大写,以便它符合APA格式,即不会大写任何不重要的单词,如a,等等 但我无法让它发挥作用。我是一名新手程序员,所以任何提示都将不胜感激。以下是我的代码:

def capitalise(phrase):
    # your code goes here to perform the word capitalisation
    p = str(phrase)
    v = p.split()

    for x in v:
        if x != "a" or x != "an" or x != "the" or x != "am" or x != "is" or x != "are" or x != "and" or x != "of" or x != "In" or x != "on" or x != "with" or x != "from" or x != "to":
            x.title()

print(x)

2 个答案:

答案 0 :(得分:0)

一个简单的例子:

unimportant=["a", "an", "the", "am" ,"is", "are", "and", "of", "in" , "on", "with", "from", "to"]


def capitalise(phrase):
    # your code goes here to perform the word capitalisation
    resp=""
    v = phrase.split()
    for x in v:
        if x not in unimportant:
            resp += (" " + x.title())
        else:
            resp += (" " + x)

    return resp

print(capitalise("This is an exeample of title"))

结果:

This is an Exeample of Title

答案 1 :(得分:0)

def capitalise(phrase): 

    doNotCap = ["a", "an", "the", "am", "is", "are", "and", "of", "in" ,"on" ,"with" ,"from" ,"to"]
    parts = phrase.split()    

    # join stuff together using ' ' which was removed by split() above
    # use a ternary to decide if something needs capitalization using .title()
    # if it is in doNotCap: use as is, else use v.title()
    return ' '.join( v if v in doNotCap else v.title() for v in parts)

k = "this is a kindof trivial test sentence to show that some words like a an the am is are and of in on with from to are not capitalized."


print(k)
print()
print(capitalise(k))

输出:

this is a kindof trivial test sentence to show that some words like a an the am is are and of in on with from to are not capitalized.

This is a Kindof Trivial Test Sentence to Show That Some Words Like a an the am is are and of in on with from to are Not Capitalized.