【问题标题】:In Python, how can I identify and replace numeric values at the start of each sentence?在 Python 中,如何识别和替换每个句子开头的数值?
【发布时间】:2018-08-20 09:26:05
【问题描述】:

目标:找出以句首开头的数字,并将原位数字更改为等于原数字加10%。

msg_orginal = """Hello, I am new here. 
2,431 other coders are new here too. 
Imagine if 2.5 were not new here? 
2,428.5 would then be new."""

我正在寻找的输出如下:

msg_revised = """Hello, I am new here. 
2,674.1 other coders are new here too. 
Imagine if 2.5 were not new here? 
2,671.35 would then be new."""

请注意三个句子中的两个如何改变了数值,但一个没有。

编辑: 请记住,相同的数字可能会在字符串中出现多次。新句子是在句号(如句号、感叹号、问号)之后或换行符之后出现的句子。

【问题讨论】:

  • @jdehesa 实际上,使用正则表达式可能更容易
  • @Student 同一个数字有可能出现两次吗?
  • @DeepSpace 是的。我已对上述内容进行了澄清。感谢您提出问题。
  • 新句子是句号之后的句子(或问号等)还是换行符之后的句子?

标签: python string python-3.x replace


【解决方案1】:

您可以将re.subr"^[\d,.]+" 之类的正则表达式一起使用,使用多行标志re.M,以便^ 匹配换行符和替换函数以进行数学运算,formatting 输出:

>>> increase = lambda m: "{:,.2f}".format(float(m.group().replace(",","")) * 1.1)

>>> print(re.sub(r"^[\d,.]+", increase, msg_orginal, flags=re.M))
Hello, I am new here. 
2,674.10 other coders are new here too. 
Imagine if 2.5 were not new here? 
2,671.35 would then be new.

这假设所有句子都从一个新行开始(并且没有句子跨越一行),就像您的示例中的情况一样。这个问题(如果有问题)可以处理separately

【讨论】:

    【解决方案2】:
    msg_orginal = """Hello, I am new here. 
    2,431 other coders are new here too. 
    Imagine if 2.5 were not new here? 
    2,428.5 would then be new."""
    
    res = []
    
    for i in msg_orginal.split("\n"):
        if i[0].isdigit():
            val = i.split()
            f = float(val[0].replace(",", ""))
            val[0] = str((f/10.0) + f)
            res.append(" ".join(val))
        else:
            res.append(i)
    
    print "\n".join(res)
    

    输出:

    Hello, I am new here. 
    2674.1 other coders are new here too.
    Imagine if 2.5 were not new here? 
    2671.35 would then be new.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-22
      • 2016-03-11
      相关资源
      最近更新 更多