You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3中如何匹配两个numpy字符串数组中的元素?

Hey there! Let’s work through this problem together. I’ll start by confirming how to generate that n-gram array you mentioned (in case you want to double-check your setup) and then show you how to pull out elements that match your location/name array.


Step 1: Generate (or Verify) Your N-gram Array

First, let’s make sure your array_one is structured correctly. Here’s a straightforward way to generate 1-gram through 5-gram from your sentence, converted to a numpy array:

import numpy as np
from nltk.util import ngrams

# Split your sentence into individual words
sentence_words = "alice in a wonder land".split()
all_ngrams = []

# Generate each n-gram type (1 to 5)
for n in range(1, 6):
    # Create n-gram tuples and convert them to space-separated strings
    gram_strings = [' '.join(gram) for gram in ngrams(sentence_words, n)]
    all_ngrams.extend(gram_strings)

# Convert to numpy array
array_one = np.array(all_ngrams)

Running this will give you an array that looks like this (truncated for brevity):

['alice', 'in', 'a', 'wonder', 'land', 'alice in', 'in a', ..., 'alice in a wonder land']


Step 2: Filter Matching Elements from Your Location/Name Array

Let’s say your second array (let’s call it location_names) has entries like ["alice", "wonder land", "land"]. To grab all elements in array_one that exactly match any entry in location_names, use numpy’s isin() function for efficient filtering:

# Example location/name array (replace with your actual data)
location_names = np.array(["alice", "wonder land", "land"])

# Get all exact matches
exact_matches = array_one[np.isin(array_one, location_names)]

print("Exact matches found:", exact_matches)

This will output:

Exact matches found: ['alice' 'land' 'wonder land']

If You Need Partial Matches

If "related elements" means elements that contain any of your location/name strings (not just exact matches), you can use a boolean mask with a list comprehension:

# Check if any location/name substring exists in the n-gram
partial_match_mask = np.array([any(name in gram for name in location_names) for gram in array_one])
partial_matches = array_one[partial_match_mask]

print("Partial matches found:", partial_matches)

This would include entries like "a wonder land" (since it contains "wonder land" and "land") along with the exact matches.


内容的提问来源于stack exchange,提问作者iam.Carrot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:25:30