如何从字符串中提取一组单词?

2024-04-25 02:14:29 发布

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

我有一个字符串是一个句子。这个句子有八个词。我想做的是,把第三个,第四个,第五个单词带到句子里。我尝试过使用索引,例如:

string[3][4][5]

但这会引起一个IndexError。我错过了什么?你知道吗


Tags: 字符串string单词句子indexerror
2条回答
# split the title string into words (split by spaces)
thead_list = page_soup.title.string.split()

# access elements with index 3, 4, 5
words = thead_list[3:6]

或者如果你只想要第三个和第五个单词,就用thead_list[2]thead_list[4]

如果需要连接提取的结果词,请执行以下操作:

new_title = " ".join(words) # converts ["word1", "word2"] to "word1 word2"

将上述所有步骤组合成一行代码:

thead = " ".join(page_soup.title.string.split()[3:6])

你可以试试这个:

thead = page_soup.title.string
final_word1, final_word2 = thead.split()[2], thead.split()[4]

相关问题 更多 >