在python中,如何基于附近的单词忽略特定的单词?

2024-05-15 21:10:22 发布

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

我有一个列表,上面的值是list=[铜、木、玻璃、金属] 字符串='小玻璃中心的木桌子,一点金属'

我需要搜索字符串中是否有特定的值,但应该忽略最不突出的值,如使用附近的单词的glass和metal。 我尝试了re.findall,我得到了木材、玻璃和金属的输出。在这种情况下,如何使用附近的关键字(如“小”和“小”)忽略“玻璃”和“金属”

预期产量=[木材]


Tags: 字符串re列表情况关键字中心单词list
1条回答
网友
1楼 · 发布于 2024-05-15 21:10:22

我的理解:我从您的问题中了解到,您试图从列表中删除紧跟在'small''little'之后的值

代码:

lst = ['Copper', 'Wood', 'Glass', 'Metal']
string = 'Wood table with small glass center,little bit of metal'
keywords = ['small','little']

punc = '''!()-[]{};:'"\, <>./?@#$%^&*_~'''
for ele in string:
    if ele in punc:
        string = string.replace(ele, " ")

lst = [stringg.lower() for stringg in lst]
string = string.lower()
lst = [word for word in lst if word.lower() in string.lower()]

words_lst = string.split(' ')

final = []
count = 0
for elem in lst:
    count = 0
    index = words_lst.index(elem)
    slice_index = index - 4 if index - 4 >= 0 else 0
    range_lst = words_lst[slice_index:index + 1]

    for keyword in keywords:
        if keyword not in range_lst and elem not in final:
            count += 1
    if count == len(keywords):
        final.append(elem)

输出:

>>> final
['wood']

相关问题 更多 >