使用一个单词数组过滤第二个数组中的单词

0 投票
6 回答
2933 浏览
提问于 2025-04-17 11:59

我正在用Python比较两个数组。

第一个数组是从查询字符串中提取的单词列表。第二个数组是要从查询中排除的单词列表。

我需要比较这两个数组,把第一个数组中包含在第二个数组里的单词去掉。

我尝试通过将第一个数组中的每个单词与第二个数组的所有单词进行比较,直到第一个数组中的所有单词都处理完为止:

for i in q_str:
    if  q_str[i] in stop_arr:
        continue
    else:
        sans_arr[j] = q_arr[i]
        j = j + 1

这里,q_str是查询数组,stop_arr包含要排除的单词,而sans_arr是一个新数组,里面是排除后的单词。

这段代码出现了一个错误:

列表索引必须是整数,而不是字符串

6 个回答

2

不太清楚你是否想要保持q_str中单词的顺序。如果你想保持顺序的话:

import re
q_str = 'I am comparing 2 arrays in python. both are character arrays. the 1st array is a list of words from a query string. the second array is the list of words to be excluded from the query.'
q_arr = re.split(r'[\s.,;]+', q_str)
stop_arr = set(['a', 'the', 'of', 'is', 'in', 'to', 'be', 'am', 'are', ''])
print [w for w in q_arr if w not in stop_arr]

这样会产生:

['I', 'comparing', '2', 'arrays', 'python', 'both', 'character', 'arrays', '1st',
 'array', 'list', 'words', 'from', 'query', 'string', 'second', 'array', 'list',
 'words', 'excluded', 'from', 'query']
9

使用集合(sets)而不是列表(lists),这样可以方便地进行集合运算,比如减法:

set1 = set(q_str)
set2 = set(stop_arr)

set3 = set1 - set2  # things which are in set1, but not in set2

# or

set4 = set1.difference(set2) # things which are in set1, but not in set2

这里有一个例子:

>>> u = set([1,2,3,4])
>>> v = set([3,4,5,6])
>>> u - v
set([1, 2])
>>> u.difference(v)
set([1, 2])
>>> v.difference(u)
set([5, 6])
1

这段代码会生成一个新数组,里面包含了所有在 q_str 中,但不在 stop_arr 中的元素:

sans_arr = [ x for x in q_str if x not in stop_arr ]

声明:我不确定 q_str 是否是一个字符串数组,因为你提到的是查询数组。

撰写回答