-1

问题

我需要在一个句子(字符串)中创建占位符。

例子

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.

将该行添加到文件末尾并从文件中取出另一行。重复这些步骤直到文件结束。

4

1 回答 1

0

既然你提到了 python,你可以这样做:

import re

myStr = "My son is 6 years old and my dad is 61 years old."
expr = r'[^#][0-9]+'
idx = 1

while True:
    try:
        match = re.search(expr,myStr)
        print match.start()
        print match.end()
        print myStr[match.start():match.end()]
        myStr = myStr[:match.start()+1] + '#' + str(idx) + myStr[match.end():]
        idx += 1
    except AttributeError:
        break

print myStr
于 2012-08-27T10:40:06.327 回答