从字符串中提取数字并替换?

时间:2018-04-08 14:48:57

标签: python

现在,我的代码按照我所知的方式正常工作。但是,我无法将一个小模块或另外几行组合在一起,从用户输入中提取一个整数,并将其膨胀为1。

dictZero = [ "zero", "none", "null", "nil" ]
dictOne = [ "juan", "one", "won" ]
dictTwo = [ "two", "to", "too", "tu" ]
dictThree = [ "three" ]
dictFour = [ "four", "fore", "for" ]

userInput = input ( "Enter your sentence to inflate: " )


for i in userInput.split():              
    for e in dictFour:
        if e in i:
            userInput = userInput.replace ( e, "five" )                
    for d in dictThree:
        if d in i:
            userInput = userInput.replace ( d, "four" )                
    for c in dictTwo:
        if c in i:
            userInput = userInput.replace ( c, "three" )                
    for b in dictOne:
        if b in i:
            userInput = userInput.replace ( b, "two" )                
    for a in dictZero:
        if a in i:
            userInput = userInput.replace ( a, "one" )


print ( userInput )

示例输入:

  

在我们1630年开始做任何事之前。

示例输出:

  

在1631年,我们开始做三件事。

如果没有过度复杂化和更改我的代码,我该怎么做才能简单地为输入字符串中的任何数字+1?

2 个答案:

答案 0 :(得分:1)

如果您忽略句子末尾的1630str.replace只能替换整行上的字词,而无需按字词拆分。

如果你想要添加十进制数字,你需要逐字逐句,这将为代码增加一些复杂性。

dictZero = [ "zero", "none", "null", "nil" ]
dictOne = [ "juan", "one", "won" ]
dictTwo = [ "two", "to", "too", "tu" ]
dictThree = [ "three" ]
dictFour = [ "four", "fore", "for" ]

userInput = input ( "Enter your sentence to inflate: " )

for i in dictFour:
    userInput = userInput.replace(i, 'five')
for i in dictThree:
    userInput = userInput.replace(i, 'four')
for i in dictTwo:
    userInput = userInput.replace(i, 'three')
for i in dictOne:
    userInput = userInput.replace(i, 'two')
for i in dictZero:
    userInput = userInput.replace(i, 'one')

output = ''
num = ''
for c in userInput:  # Going char by char to find decimal values
    if c.isdigit():  # is this char a digit?
        num += c  # if so remember it
    else:
        if num: # if we just found a whole number
            output += str(int(num) + 1) # add 1 and append the string
        num = ''
        output += c  # Append any non-decimal character


print(output)

输入:

  

在我们1630年开始做任何事之前。

输出:

  

在1631年,我们开始做三件事。

请注意,这不会在字符串中添加float或负值,只会int s。

答案 1 :(得分:0)

标准不清楚,我就是这样做的。

import re

word_dict = dict.fromkeys(["zero", "none", "null", "nil"], 'one')
word_dict.update(dict.fromkeys([ "juan", "one", "won" ], 'two'))
word_dict.update(dict.fromkeys([ "two", "to", "too", "tu" ], 'three'))
word_dict.update(dict.fromkeys([ "three" ], 'four'))
word_dict.update(dict.fromkeys([ "four", "fore", "for" ], 'five'))

userInput = input ( "Enter your sentence to inflate: " )

for i in word_dict.keys():
    userInput = re.sub(i, word_dict[i], userInput)
digits = re.compile(r'\d+')
userInput = digits.sub(lambda m: str(int(m.group(0)) + 1), userInput)

print ( userInput )

示例运行:

  

输入你的句子来膨胀:'在我们开始在1630年做任何事之前。'

     

Befivee我们在1631开始做三件事。