使用单词数组从第二个数组中筛选单词

2024-04-26 18:41:21 发布

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

我在比较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是一个排除了单词的新数组。在

此代码生成错误:

list indices must be integers not str


Tags: 字符串in列表forif错误数组单词
3条回答

使用集合而不是列表,这样可以方便地访问集合操作,例如减法:

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

下面是一个例子:

^{pr2}$

此代码使用q_str中不存在的q_str元素生成新数组:

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

免责声明:我不知道qu str是否是一个字符串数组,因为你谈论的是一个查询数组。在

您是否希望保留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]

这会产生:

^{pr2}$

相关问题 更多 >