【发布时间】:2023-04-08 07:48:01
【问题描述】:
问题
我需要在句子(字符串)中创建占位符。
示例
My son is 6 years old and my dad is 61 years old.
My son is #0 years old and my dad is #1 years old.
这只是一句话。句子逐行分隔,并包含句子中数字和(数字位置混合且长度不同)的不同位置。
我尝试过使用各种代码,但其中大多数都适用于模式替换。 我知道程序,如果我在 python 编程方面更有经验,我可以做到。
程序
阅读句子(文本文件中的行)。计算句子中数字(d+)的数量,如果句子包含 6 个数字,则从句子中的最后一个数字开始替换到第一个数字(#6、#5、#4、...)。
举例
My dog is 3 years old, 92.4 cm heigh and has 16 teeth.
数不同长度的数字个数(1a,1b1,1c11,1111,1.1是8个数字):4个。
1.循环(替换第 4 个数字):
My dog is 3 years old, 92.4 cm heigh and has #4 teeth.
2。循环:
My dog is 3 years old, 92.#3 cm heigh and has #4 teeth.
3.循环:
My dog is 3 years old, #2.#3 cm heigh and has #4 teeth.
4.循环:
My dog is #1 years old, #2.#3 cm heigh and has #4 teeth.
将该行添加到文件末尾并从文件中取出另一行。 重复这些步骤直到文件结束。
【问题讨论】:
-
不要在正则表达式中这样做。看起来也很像家庭作业,但无论如何,不要使用正则表达式。
-
应该是什么语言?为什么循环会向后运行?
-
如果您的字符串包含文字 #N 会发生什么,例如“儿子 #1 6 岁”。文字“#1”应该被替换/转义,还是留在里面?
标签: python regex placeholder substitution