【问题标题】:How to capitalize the first letter of every sentence?如何将每个句子的第一个字母大写?
【发布时间】:2014-05-13 02:00:53
【问题描述】:

我正在尝试编写一个将每个句子的第一个字母大写的程序。这是我到目前为止所拥有的,但我无法弄清楚如何在句子之间添加句点。例如,如果我输入:

你好。再见

输出是

你好,再见

这个时期消失了。

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

【问题讨论】:

    标签: python python-3.x capitalization


    【解决方案1】:

    如果你只想让句子的第一个字母大写,而不改变句子的其余部分,那么你可以获取第一个字符,然后将其转换为大写并与其余部分连接句子,如下所示:

    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!
    

    【讨论】:

    • 这只会将第一个单词大写。
    【解决方案2】:

    你可以使用,

    In [25]: st = "this is first sentence. this is second sentence. and this is third. this is fourth. and so on"
    
    In [26]: '. '.join(list(map(lambda x: x.strip().capitalize(), st.split('.'))))
    Out[26]: 'This is first sentence. This is second sentence. And this is third. This is fourth. And so on'
    
    In [27]:
    

    【讨论】:

    • OP 希望将每个句子的首字母大写,而不是每个单词。
    • . 被认为是句子的结尾。所以"this is first. second .third" 是三个不同的句子。
    • OP 想要“这是第一句话。”,而不是“这是第一句话。”
    【解决方案3】:

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

        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+。

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

      • 这会在末尾添加一个额外的句点
      【解决方案5】:

      似乎很多人都懒得检查缩进或代码,而是先运行它来检查错误。关于句子中第一个单词的大写,而句子中的其他单词要保持大写,这个问题肯定已经被其他回答的人弄丢了。如果您想完成此操作,请尝试以下代码,该代码将在重复菜单上运行,直到选择退出:

      # 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()
      

      【讨论】:

        【解决方案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)
        

        输出

        请输入一个/多个句子:
        句号可能出现在句子中,例如,看!并且句子可能
        结束没有点!
        ['句号可能出现在句子中,例如,看!',
         '并且句子可能没有点结束!']

        【讨论】:

          【解决方案7】:

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

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

          【讨论】:

          • 如果您的答案太短而无法被接受,这可能有助于解释您试图提出的错误。
          【解决方案8】:
          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. 
          

          【讨论】:

            【解决方案9】:

            试试这个:

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

            【讨论】:

            • 此代码 sn-p 将单词的每个首字母大写。例:你好。你好吗。很高兴见到你。
            【解决方案10】:

            这应该可行:

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

            【讨论】:

              【解决方案11】:

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

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

              光滑,对吧?

              【讨论】:

              • 我不这么认为。 str.title 大写每个单词,而不是每个句子。
              • 如果您在末尾的句点之后没有字母,则会给出索引超出范围错误。
              【解决方案12】:

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

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

              这个正则表达式包含一个肯定的后向断言(?&lt;=...),它匹配.?!,后跟一个空格字符\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+))')
              

              【讨论】:

                【解决方案13】:

                也许你可以这样做:

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

                【讨论】:

                • 这只会将第一个单词大写。
                【解决方案14】:

                你只需要改变一行:

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

                【讨论】:

                  【解决方案15】:

                  可能是这样的:

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

                  【讨论】:

                  • capitalize() 仅将第一个字母大写,并将该句子中的所有其他单词转换为小写。是的,甚至是名词。
                  猜你喜欢
                  • 2019-09-04
                  • 2012-06-23
                  • 2011-07-20
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2021-01-13
                  • 1970-01-01
                  相关资源
                  最近更新 更多