gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:33:47 35 4
gpt4 key购买 nike

据我所知,现在我的代码正在按预期工作。但是,我无法组合一个小模块或另外几行来从用户输入中提取整数并将其增加 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 )

示例输入:

Before we begin to do anything at 1630.

示例输出:

Befive we begin three do anything at 1631.

在不过度复杂化和显着改变我的代码的情况下,我可以做什么来简单地对输入字符串中的任意数字+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)

输入:

Before we begin to do anything at 1630.

输出:

Befive we begin three do anything at 1631.

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

关于python - 从字符串中提取数字并替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49719139/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com