假设我有这样一段话
I have two years left for my school to end.
I have four apples at home. My school sucks but it is the second best school in town.
I have three years left for my school to end.
I have four apples at home. My school sucks but it is the second best school in town.
我想做以下工作:
1)将段落解构成句子
2) 找出哪个句子中有“school”一词,并提取该句子
3) 对于所有提取的句子,找出其中有数字的句子(例如1、2、3等)
4) 找出第一个数字是什么,然后提取这个数字
目前,我有以下代码,但我相信有一个更好的更优雅的方式去做这件事
txt = 'I have two years left for my school to end.
I have four apples at home. My school sucks but it is the second best school in town. I have three years left for my school to end.
I have four apples at home. My school sucks but it is the second best school in town.'
words = 'school'.split(' ')
sentences = re.findall(r"([^.]*\.)" ,txt)
for sentence in sentences:
if any(word in sentence for word in words):
print(sentence.split('\n'))
上面代码的输出
['I have two years left for my school to end.']
[' My school sucks but it is the second best school in town.']
[' I have three years left for my school to end.']
[' My school sucks but it is the second best school in town.']
期望的输出是
two
three
虽然你的尝试并不准确,但我认为你至少做了一次尝试,所以这里有一个解决方案: -创建一个要筛选的单词列表,下面的数字[],并对照它进行检查
输出:
相关问题 更多 >
编程相关推荐