找出句子中的第一个数字词

2024-10-05 12:24:55 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这样一段话

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

Tags: thetoinforismyhaveit
1条回答
网友
1楼 · 发布于 2024-10-05 12:24:55

虽然你的尝试并不准确,但我认为你至少做了一次尝试,所以这里有一个解决方案: -创建一个要筛选的单词列表,下面的数字[],并对照它进行检查

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."
numbers = ["one","two","three", "four","five","six","seven","eight","nine"]
sentences = txt.split('.')
words = []

for i in sentences:
    words = i.split()

    # below checks whether the words in the sentence are in the list, numbers[]
    num = [k for k in words if k in numbers]

    if "school" in words and any(num):
        print(num[0])

输出:

two
three

相关问题 更多 >

    热门问题