在句子中查找短语

2024-09-27 21:28:20 发布

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

我必须做一个程序,必须找到一个句子中的短语与用户指定的关键字:

The Large Hadron Collider (LHC) is the world’s largest and most powerfulparticle accelerator.This site includes the latest news from the project, accessible explanations of how the LHC works, how it is funded, who works there and what benefits it brings us.You can access a wide range of resources for the public, journalists and teachers and students, there are also many links to other sources of information.The Large Hadron Collider atCERNnear Geneva, Switzerland is opening new vistas on the deepest secrets of the universe, stretching the imagination with newly discovered forms of matter, forces of nature, and dimensions of space.

用户指定:

^{pr2}$

我不知道如何在变量中的关键字前后提取几个单词 例如:

keyword = 'large'

它必须返回

The Large Hadron

句子中出现了大的。在一个句子中,我怎样才能把一个词放在变量前面,一个词放在后面?在


Tags: andofthe用户isit关键字句子
3条回答

使用index来获取关键字的位置,然后将字符串从关键字的任一侧切分一个单词。在

In [1]: s = 'The Large Hadron Collider (LHC) is the world’s largest and most powerfulparticle accelerator.'
In [2]: words = s.split() 
In [3]: words_lower = s.lower().split() #lowercase words so keyword matching is easy.
In [4]: keyword = 'large'
In [5]: i = words_lower.index(keyword)
In [6]: phrase = ' '.join(words[i-1:i+2])
In [7]: phrase
Out[7]: 'The Large Hadron'
text = "The Large Hadron Collider (LHC) is the world’s largest and most powerfulparticle accelerator.This site includes the latest news from the project, accessible explanations of how the LHC works, how it is funded, who works there and what benefits it brings us.You can access a wide range of resources for the public, journalists and teachers and students, there are also many links to other sources of information.The Large Hadron Collider atCERNnear Geneva, Switzerland is opening new vistas on the deepest secrets of the universe, stretching the imagination with newly discovered forms of matter, forces of nature, and dimensions of space."
keywords = ['large', 'is', 'most']
text = text.lower().split(' ')
results = []
for word in keywords:
    indx = text.index(word)
    results.append(" ".join(text[indx-1:indx+2]))

print results
test_word = 'large'
my_string = 'The Large Hadron Collider (LHC) is the world’s largest and most powerfulparticle accelerator.This site includes the latest news from the project, accessible explanations of how the LHC works, how it is funded, who works there and what benefits it brings us' 
# I truncated your sentence

test_words = my_string.lower().split()
correct_case = my_string.split() # this will preserve the case of the original words
# and it will be identical in length to test words with each word in the same position
position = test_words.index(test_word)

my_new_string = ' '.join(correct_case[position-1:position+2]

为了清楚这两个列表有相同的单词,测试单词列表虽然将所有内容都以小写形式保存,但测试单词将位于每个列表中的相同位置,因此您可以使用测试单词列表中的位置从正确的单词列表中提取正确的单词。在

相关问题 更多 >

    热门问题