gpt4 book ai didi

python - 如何从句子中提取单词并检查其中是否不存在单词

转载 作者:行者123 更新时间:2023-12-05 08:36:11 24 4
gpt4 key购买 nike

下面是我的代码。我需要从用户那里获取输入(一个句子)并检查其中是否有从 0 到 10 的任何数字。我知道有很多方法可以解决它,例如split()isalnum() 等,但我只需要帮助将它们组合在一起。请在下面找到我的代码:

sentence1 = input("Enter any sentence (it may include numbers): ")
numbers = ["1","2","3","4","5","6","7","8","9","10","0"]

ss1 = sentence1.split()
print(ss1)
if numbers in ss1:
print("There are numbers between 0 to 10 in the sentece")
else:
print("There are no numbers in the sentence”)

谢谢:)

编辑:预期输出应该是这样的:

Enter any sentence (it may include numbers): I am 10 years old
There are numbers between 0 and 10 in this sentence

最佳答案

我会使用正则表达式:

def contains_nums(s):
import re
m = re.search('\d+', s)
if m:
return f'"{s}" contains {m.group()}'
else:
return f'"{s}" contains no numbers'

例子:

>>> contains_nums('abc 10')
'"abc 10" contains 10'

>>> contains_nums('abc def')
'"abc def" contains no numbers'

注意。这只是检查第一个 号码,使用re.findall如果你需要全部。这也是在单词中查找数字,如果您只想要单独的数字,请使用带有单词边界的正则表达式( \b\d+\b ),最后,如果您想限制为 0-10 个数字,请使用 (?<!\d)1?\d(?!\d) (或 \b(?<!\d)1?\d(?!\d)\b 表示独立数字)

更完整的解决方案
def contains_nums(s, standalone_number=False, zero_to_ten=False):
import re

regex = r'(?<!\d)1?\d(?!\d)' if zero_to_ten else '\d+'

if standalone_number:
regex = r'\b%s\b' % regex

m = re.search(regex, s)
if m:
return f'"{s}" contains {m.group()}'
else:
a = "standalone " if standalone_number else ""
b = "0-10 " if zero_to_ten else ""
return f'"{s}" contains no {a}{b}numbers'
>>> contains_nums('abc100', standalone_number=False, zero_to_ten=False)
'"abc100" contains 100'

>>> contains_nums('abc100', standalone_number=True, zero_to_ten=False)
'"abc100" contains no standalone numbers'

>>> contains_nums('abc 100', standalone_number=True, zero_to_ten=True)
'"abc 100" contains no standalone 0-10 numbers'

关于python - 如何从句子中提取单词并检查其中是否不存在单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69941488/

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