在单词列表中查找单词索引

2024-05-29 04:22:22 发布

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

对于生物标记问题,我正在寻找一种在字符串列表中查找特定单词索引的方法

例如:

text = "Britain has reduced its carbon emissions more than any rich country"
word = 'rich'
print(text.split())
['Britain', 'has', 'reduced', 'its', 'carbon', 'emissions', 'more', 'than', 'any', 'rich', 'country']

text.split(' ').index(word) # returns 9

text.split(' ').index('rich country') # occurring an error as expected 

我希望的答案是:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]

我想我可以使用循环找到第一个单词的索引和最后一个单词的索引,然后将它们替换为0或1

但是,我的问题是,如果text列表如下所示,该怎么办:

['Britain', 'has', 'reduced', 'its', 'carbon', 'emissions', 'more', 'than', 'any', 'rich', 'count', '_ry']

或许

['Britain', 'has', 'reduced', 'its', 'carbon', 'emissions', 'more', 'than', 'any', 'richcountry']

我相信我可以通过使用dirty for循环来解决这个问题,但我相信还有另一种干净简单的方法来解决这个问题

如果你们能就这个问题给我一些建议,我将不胜感激

提前谢谢


Tags: text列表moreany单词countryitssplit
1条回答
网友
1楼 · 发布于 2024-05-29 04:22:22

在回答你的第一个问题时:

text = "Britain has reduced its carbon emissions more than any rich country"
words = 'rich country'.split(" ")
split_text = text.split()
[1 if x in words else 0 for x in split_text]

输出:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]

第二个问题需要模糊匹配,这可以通过fuzzywuzzy实现:

from fuzzywuzzy import process
words = 'rich country'.split(" ")
split_text = ['Britain', 'has', 'reduced', 'its', 'carbon', 'emissions', 'more', 'than', 'any', 'richcountry']
[1 if process.extractBests(x, words, score_cutoff = 60) else 0 for x in split_text]

输出:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 1]

以及

split_text = ['Britain', 'has', 'reduced', 'its', 'carbon', 'emissions', 'more', 'than', 'any', 'rich', 'count', '_ry']
[1 if process.extractBests(x, words, score_cutoff = 60) else 0 for x in split_text]

输出:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]

请注意,您可以使用score_cutoff设置阈值

相关问题 更多 >

    热门问题