[英]Python - Extract Number From String Without Square Bracket
因此,我目前正在开发AI,但我需要年龄的帮助。 因此,如果有人输入“我14岁”,我希望它取14并设置一个变量。 我已经做到了,但是,方括号放在输出中,这是我不想要的,所以我正在寻找一种方法,从没有方括号的字符串中获取数字。 这是我的代码
#Gets users age
elif "i am" in inp and "years old" in inp:
age=[int(s) for s in inp.split() if s.isdigit()]
age=str(age)
print(age)
任何帮助表示赞赏
使用正则表达式:
import re
m = re.search("\d+", "I am 14 years old")
if m:
print(int(m.group()))
输出:
14
做就是了
age=[s for s in inp.split() if s.isdigit()]
int(''.join([str(s) for s in age]))
1.使用您的方法:
只需使用较少的“紧凑”语法:
#!/usr/bin/python
inp="i am 15 years old"
#Gets users age
if "i am" in inp and "years old" in inp:
for s in inp.split():
if s.isdigit():
age=int(s)
print(age)
运行这段代码可以得到:
$ python pouet.py
15
2.使用正则表达式
正则表达式更适合此类任务。 下面的代码解析用户的年龄,即使他已经1岁(没有“ s”),或者他将“ i am”缩写为“ i'm”:
#!/usr/bin/python
import re
test_v=[ "i am 15 years old", "i'm 1 year old"]
#Gets users age
for test_string in test_v:
res = re.match('(i am|i\'m) (\d+) year[s]? old', test_string)
if (res):
print res.group(2)
运行这段代码可以得到:
$ python pouet.py
15
1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.