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.
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']
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

