我正在制作AI,我希望代码能够理解某些东西是一个整数
elif inp==("i am", int):
print("You are "x" years old")
inp
是我的变量
elif="i am", int ,"years old":
print("You are", int ,"years old")
这就是我想要的。但是为了实际工作,我希望它能理解那里有一个整数。
如果他们说" I am awesome
"它会这样做,但如果他们把#34; I am 14
"它会打印You are "x" years old
。我对打印位和他们实际的年龄感到满意。但是,我只想让代码识别出那里有一个数字。
答案 0 :(得分:1)
给定简单文本,提取整数(python 3代码)相当容易:
import re
while True:
# I have no idea where your text is coming from, this is for testing
line = input("enter text: ")
if not line: break
# The regular depression means "one or more characters in the range 0-9"
m = re.search(r'([0-9]+)', line)
if m:
print(m.groups()[0]) # << This hold the integer string
# if m is false, there is no integer
如果可能有多个整数,则可能需要不同的解决方案。
答案 1 :(得分:0)
如果您的输入字符串始终采用相同的格式,即最后一个字将是整数或其他字符。你可以尝试:
my_input_list = my_input.split() # Split your sentence into list
last_word = my_input_list[-1] # Get last word
if isinstance(last_word , int): # Check is last word in "int" type
print("You are {age}" years old)
else:
print(my_input)
但在编写AI
时,您的代码将来会变得更复杂。您应该使用regex
作为@Rakesh提及进行探索。
答案 2 :(得分:0)
在打印前添加类型验证,如果您愿意,还可以添加raise
TypeError
或InputError
。
if type(age) == type(1):
#continue with printing
else:
raise InputError('age must be an integer)
或者更好的是print('age must be an integer ')
而不是提出错误