字符串操作:将每个句子的首字母大写

时间:2014-04-02 02:28:13

标签: python python-3.x

我试图编写一个程序,将每个句子的第一个字母大写。这是我到目前为止所做的,但我无法弄清楚如何在句子之间添加句号。例如,如果我输入:你好。再见,输出是Hello Goodbye,时间已经消失。

string=input('Enter a sentence/sentences please:')
sentence=string.split('.')
for i in sentence:
    print(i.capitalize(),end='')

15 个答案:

答案 0 :(得分:6)

你可以use nltk for sentence segmentation

#!/usr/bin/env python3
import textwrap
from pprint import pprint
import nltk.data # $ pip install http://www.nltk.org/nltk3-alpha/nltk-3.0a3.tar.gz
# python -c "import nltk; nltk.download('punkt')"

sent_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
text = input('Enter a sentence/sentences please:')
print("\n" + textwrap.fill(text))
sentences = sent_tokenizer.tokenize(text)
sentences = [sent.capitalize() for sent in sentences]
pprint(sentences)

输出

Enter a sentence/sentences please:
a period might occur inside a sentence e.g., see! and the sentence may
end without the dot!
['A period might occur inside a sentence e.g., see!',
 'And the sentence may end without the dot!']

答案 1 :(得分:4)

也许是这样的:

print('.'.join(i.capitalize() for i in sentence))

答案 2 :(得分:2)

您可以使用正则表达式。 定义与句子的第一个单词匹配的正则表达式:

import re
p = re.compile(r'(?<=[\.\?!]\s)(\w+))

此正则表达式包含一个正面的后置断言(?<=...),它与.?!匹配,后跟空格字符\s。接下来是一个匹配一个或多个字母数字字符\w+的组。实际上,匹配句子结尾后的下一个单词。

您可以定义一个将正则表达式匹配对象大写的函数,并将此函数提供给sub()

def cap(match):
    return(match.group().capitalize())

p.sub(cap, 'Your text here. this is fun! yay.')

您可能希望对与字符串开头的单词匹配的另一个正则表达式执行相同的操作:

p2 = re.compile(r'^\w+')

或者通过组合它们来使原始正则表达式更难阅读:

p = re.compile(r'((?<=[\.\?!]\s)(\w+)|(^\w+))')

答案 3 :(得分:2)

这应该有效:

import re
text = raw_input("Enter text: ")
rtn = re.split('([.!?] *)', text)
final = ''.join([i.capitalize() for i in rtn])
print final

答案 4 :(得分:1)

你只需改变一行:

string=input('Enter a sentence/sentences please:')
sentence=string.split('.')
for i in sentence:
    print (i.strip().capitalize()+". ",end='')

答案 5 :(得分:1)

x = 'hello. goodbye. and how are you doing.'
print( '. '.join(map(lambda s: s.strip().capitalize(), x.split('.'))))

# Hello. Goodbye. And how are you doing. 

答案 6 :(得分:0)

好的,所以我的第一个答案完全错了。这是你可以使用的另一个答案,它也向你展示了python的一些更强大的功能。假设您的字符串存储在s中,其中所有句子都在一个逗号分隔的单个字符串中。以下代码返回相同的完整字符串,以句点分隔,但每个句子的首字符大写。

'.'.join(map((lambda x: x[0].upper()+x[1:]), s.replace('. ','.').split('.')))

光滑,对吗?

答案 7 :(得分:0)

您可以使用title()字符串对象的方法。

title()会返回string的副本,其中每个单词的第一个字母 是大写的,所有其他字母都是小写的;

例如,

       >>string=input('Enter a sentence/sentences please:')
       Enter a sentence/sentences please:"hello. goodbye"
       >>string.title()

输出:

'Hello. Goodbye'

另一个例子,

   >>string=input('Enter a sentence/sentences please:')
   Enter a sentence/sentences please:"this is first sentence. this is second sentence. and this is third. this is fourth. and so on"
   >>string.title()

输出:

'This Is First Sentence. This Is Second Sentence. And This Is Third. This Is Fourth. And So On'

答案 8 :(得分:0)

也许你可以这样做:

string=input('Enter a sentence/sentences please:')
sentence='.'.join([i.capitalize() for i in string.split('.')])
print(sentence)

答案 9 :(得分:0)

试试这个:

x = 'hello. how are you doing. nice to see. you'
print '.'.join(map(lambda x: x.title(), x.split('.')))

答案 10 :(得分:0)

您可以在打印功能中使用end='.'

print(i.capitalize(),end='.')

答案 11 :(得分:0)

似乎许多人不必先通过运行它来检查缩进或代码来检查错误。关于句子中第一个单词的大写字母在句子中具有REMNAL资本化的句子,对于响应的其他人来说,问题必定已经丢失。如果要完成此操作,请尝试以下代码,该代码将在重复菜单上运行,直到选择退出:

# Purpose: Demonstrate string manipulation.
#
# ---------------------------------------------------------------
# Variable          Type        Purpose
# ---------------------------------------------------------------
# strSelection      string      Store value of user selection.
# strName           string      Store value of user input.
# words             string      Accumulator for loop.


def main():
    print()
    print("-----------------------------------------------------")
    print("|             String Manipulation                   |")
    print("-----------------------------------------------------")
    print()
    print("1: String Manipulation")
    print("X: Exit application")
    print()
    strSelection = input("Enter your menu selection: ")
    if strSelection == "1":
        strName = input("Enter sentence(s) of your choosing:  ")
        strSentences = ""
        words = list(strName.split(". ")) # Create list based on each sentence.
        for i  in range(len(words)): # Loop through list which is each sentence.
            words[i] = words[i].strip() # Remove any leading or trailing spaces.
            words[i] = words[i].strip(".") # Remove any periods.

            words[i] = words[i][:1].upper() + words[i][1:] # Concatenate string with first letter upper.
            strSentences += words[i] + ". " # Concatenate a final string with all sentences.

        # Print results.
        print("Sentences with first word capitalized, \
and other caps left intact: ", strSentences) 
        print()
        main() # Redisplay menu.

    # Bid user adieu.
    elif strSelection.upper() == "X":
        print("Goodbye")
    else:
        print ("Invalid selection")
        main() # Redisplay menu.

main()

答案 12 :(得分:0)

该程序用于大写每个新句子的第一个单词。

def sentenceCapitalizer():

    string===input('Enter a sentence/sentences please:')
    sentence=string.split('.')
    for i in sentence:
        print (i.strip().capitalize()+". ",end='')
sentenceCapitalizer()

答案 13 :(得分:0)

在搜索和调整了几个小时后,我遇到了同样的问题。我终于找到了一个近乎完美的解决方案,然而,它解决了手头的问题。

    original_data = raw_input("Enter text: ")
    list = original_data.split(".")
    if original_data.endswith('.'):
        list.remove('')

    for w in list:
        stripper= w.strip().capitalize() +"."
        print stripper,

这段代码的作用是将输入作为字符串并使用split()函数将其转换为字符串数组。然后遍历该数组以提取每个字符串并在完全停止后将第一个字符大写。

让我们说你输入的东西,比如:

hello stackoverflow. hi robot. we're here, devmike.

它会输出:

Hello stackoverflow. Hi robot. We're here, devmike.

注意:我只用python2.7 +测试过这个,但你可以修改它以适应3 +。

答案 14 :(得分:0)

如果您只想将句子的首字母大写,而不更改其余句子,则可以获取第一个字符,然后将其转换为大写并与其余字符连接句子,如下所示:

desc="please make only the first letter Upper Case, and do not change the rest!"
desc = desc[0].upper()+desc[1:]
print(desc)

输出将是:

Please make only the first letter Upper Case, and do not change the rest!