【问题标题】:Uppercasing letters after '.', '!' and '?' signs in Python'.'、'!' 后面的大写字母和 '?' Python中的标志
【发布时间】:2017-01-15 14:05:16
【问题描述】:

我一直在搜索 Stack Overflow,但找不到正确的纠正代码,例如

"hello! are you tired? no, not at all!"

进入:

"Hello! Are you tired? No, not at all!"

【问题讨论】:

  • .!?等字符处拆分字符串。将每个结果部分大写。将各部分连接回一个字符串。准备好了。
  • @Elgaard> stackoverflow 既不是编码服务,也不是熟代码解决方案数据库。它是关于互相帮助解决在解决问题时遇到的精确问题。因此,开始自己编写代码,如果遇到特定问题,请返回特定问题。
  • @spectras... 哇,您的回复很棒!听我是丹麦 DTU 的一名工程师(第三学期),并开始了 Python 课程。我不是像你这样的专业人士,但我尝试在网上查找信息。已经为我自己做了很多编程!很抱歉毁了你的一天。
  • @Elgaard> 完全没有破坏。祝您培训顺利,如果遇到困难,请随时询问a good question。当觉得问题很有趣时,整个社区都会乐于提供帮助。这与初学者无关,许多初学者提出了惊人的问题,无数“专业人士”提出了糟糕的问题。你可能也对this answer 感兴趣(向下滚动到“询问家庭作业”)。无论如何,在你的课堂上玩得开心:)。

标签: python uppercase


【解决方案1】:

您可以尝试这种正则表达式方法:

import re
re.sub("(^|[.?!])\s*([a-zA-Z])", lambda p: p.group(0).upper(), s)
# 'Hello! Are you tired? No, not at all!'

  • (^|[.?!]) 匹配字符串的开头 ^.?! 后跟可选空格;
  • [a-zA-Z] 直接匹配第一个模式之后的字母;
  • 使用 lambda 函数将捕获的组转换为大写;

【讨论】:

    【解决方案2】:
    1. 使用正则表达式在标点符号处分割
    2. 在句子开头用大写字母连接所有内容。

    例如这样:

    import re
    text = 'hello! are you tired? no, not at all!'
    
    punc_filter = re.compile('([.!?]\s*)')
    split_with_punctuation = punc_filter.split(text)
    
    final = ''.join([i.capitalize() for i in split_with_punctuation])
    print(final)
    

    输出:

    >>> Hello! Are you tired? No, not at all!
    

    【讨论】:

      【解决方案3】:

      capitalize() 方法使除第一个以外的所有字母都变小。

      更一般的变体是:

      def capitalize(text):
          punc_filter = re.compile('([.!?;]\s*)')
          split_with_punctuation = punc_filter.split(text)
          for i,j in enumerate(split_with_punctuation):
              if len(j) > 1:
                  split_with_punctuation[i] = j[0].upper() + j[1:]
          text = ''.join(split_with_punctuation)
          return text
      
      text = "hello Bob! are you tired? no, not at all!"
      capitalize(text)
      

      输出:

      'Hello Bob! Are you tired? No, not at all!'
      

      【讨论】:

      • 重要的是,此解决方案不会使句子内部的专有名称小写。
      【解决方案4】:

      你可以这样做

      x = "hello! are you tired? no, not at all!"
      y = x.split("? ")
      z="" 
      for line in y:
          z = "{} {}".format(z,line.capitalize())
      print(z)
      

      并根据您的需要进行调整。

      【讨论】:

      • 谢谢RnRoger! :) 我会试试的。
      • np ^^。不过,我没有让它与多个拆分字符一起使用。 (例如“?”和“!”)
      猜你喜欢
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 2019-08-08
      • 2015-10-24
      • 2021-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多