Using a set would be much faster than iterating through the lists.
checklist = ['A', 'FOO']
words = ['fAr', 'near', 'A']
matches = set(checklist).intersection(set(words))
print(matches) # {'A'}
Answer from Michelle Welcks on Stack OverflowUsing a set would be much faster than iterating through the lists.
checklist = ['A', 'FOO']
words = ['fAr', 'near', 'A']
matches = set(checklist).intersection(set(words))
print(matches) # {'A'}
This will get you a list of exact matches.
matches = [c for c in checklist if c in words]
Which is the same as:
matches = []
for c in checklist:
if c in words:
matches.append(c)
I have this list I am trying to find a exact match for using a list comprehension.
my_list =['abc','abc_ab'] result = [i for i in my_list if 'abc_a' in i ] the list is finding and matching on abc_ab
I want to match abc_a not abc_ab. how do I use a list comprehension to match on the exact phrase.
wait never mind. I needed == not in.
Is there a way to match a list of strings exactly with the strings in a pandas column to filter out the ones that do not have?
Say, words = ['ab', 'ml']
df =
| data |
|---|
| 'example string ab' |
| 'absolute value' |
After filtering, I must get only the row with value 'example string ab' for it contains exact string 'ab' from the list 'words'.
Hi, I don't get why when I use str.contains to get exact matches from a list of keywords, the output still contains partial matches. Here is an extract of what I have (I'm only including one keyword in the list for the example):
keyword= ['SE.TER.ENRL']
subset = df[df['Code'].str.contains('|'.join(keyword), case=False, na=False)]
Output: ['SE.TER.ENRL' 'SE.TER.ENRL.FE' 'SE.TER.ENRL.FE.ZS']
Does anyone know how to get around this?
Thanks!
You can use in directly on the list.
Ex:
mylist = ['cathrine', 'joey', 'bobby', 'fredrick']
if 'cat' in mylist:
print 'Yes it is in list'
#Empty
if 'joey' in mylist:
print 'Yes it is in list'
#Yes it is in list
You can use in with if else conditional operator
In [43]: mylist = ['cathrine', 'joey', 'bobby', 'fredrick']
In [44]: 'yes in list ' if 'cat' in mylist else 'not in list'
Out[44]: 'not in list'
It looks like you need to perform this search not only once so I would recommend to convert your list into dictionary:
>>> l = ['Hi, hello', 'hi mr 12345', 'welcome sir']
>>> d = dict()
>>> for item in l:
... for word in item.split():
... d.setdefault(word, list()).append(item)
...
So now you can easily do:
>>> d.get('hi')
['hi mr 12345']
>>> d.get('come') # nothing
>>> d.get('welcome')
['welcome sir']
p.s. probably you have to improve item.split() to handle commas, point and other separators. maybe use regex and \w.
p.p.s. as cularion mentioned this won't match "welcome sir". if you want to match whole string, it is just one additional line to proposed solution. but if you have to match part of string bounded by spaces and punctuation regex should be your choice.
>>> l = ['Hi, hello', 'hi mr 12345', 'welcome sir']
>>> search = lambda word: filter(lambda x: word in x.split(),l)
>>> search('123')
[]
>>> search('12345')
['hi mr 12345']
>>> search('hello')
['Hi, hello']
fruitlist is a string, not a list.
fruitlist = str(sys.argv[2:]).upper() converts the sys.argv to str then applies the upper case.
to avoid this you can do this instead:
fruitlist = [x.upper() for x in sys.argv[2:]]
full code:
import sys
fruitlist = [x.upper() for x in sys.argv[2:]]
print(sys.argv[1])
print(fruitlist)
if sys.argv[1].strip() in fruitlist:
print(sys.argv[1], 'exact match found in list')
Your fruitlist isn't actually a list; it is a string. Here is the correct code, which makes it a list not a string:
import sys
fruitlist = [str(a).upper() for a in sys.argv[2:]]
print(sys.argv[1])
print(fruitlist)
if sys.argv[1].strip() in fruitlist:
print(sys.argv[1], 'exact match found in list')
Try this:
def replacer():
my_words = my_string.split(" ")
result = []
for key, value in dictionary.items():
for item in value:
if item == my_words[0]:
result.append(key + " to me " + " ".join(my_words[1:]))
return result
How about doing it this way:-
def replacer(ms, md):
tokens = ms.split()
firstWord = tokens[0]
for k, v in md.items():
if firstWord in v:
return k + ' ' + ' '.join(tokens[1:])
myString = 'happen this news on TV'
myDict = {'happen1':['happen later'], 'happen2':['happen'], 'happen3':['happen later',' happen tomorrow'], 'happen4':['happen now'], 'happen5':['happen again','never happen']}
print(replacer(myString, myDict))
I hate to tell you this, but you're overthinking it - you can just use the regular == operator for this:
list1_element_1: ['GigabitEthernet0/6/4/1']
list2_element_1: ['GigabitEthernet0/6/4/1.100']
list3_element_1: ['GigabitEthernet0/6/4/1']
print(list1_element_1 == list2_element_1) # False
print(list1_element_1 == list3_element_1) # True
For strings, the == operator returns True if they match exactly. For lists, it returns True if the lengths are the same and corresponding elements match exactly (the .__eq__() method is used for this comparison, if you're trying to compare custom classes - all built-in classes have their notions of equality implemented). So if you have a list of strings, you can test whether or not it's equal to another list of strings:
print(['str1', 'str2', 'str3'] == ['str1', 'str2', 'str3']) # True
print(['str1', 'str2', 'str3'] == ['str1', 'str3', 'str2']) # False
Just use:
def find_word(text, search):
return text == search
A much better idea for exact matches is to store the keywords in a set
keywords = {'foo', 'bar', 'joe', 'mauer'}
listOfStrings = ['I am frustrated', 'this task is foobar', 'mauer is awesome']
[s for s in listOfStrings if any(w in keywords for w in s.split())]
This only tests each word in listOfStrings once. Your method (or using regex) looks at every word in listOfStrings for each keyword. As the number of keywords grows, that will be very inefficient.
Instead of checking if each keyword is contained anywhere in the string, you can break the sentences down into words, and check whether each of them is a keyword. Then you won’t have problems with partial matches.
Here, RE_WORD is defined as the regular expression of a word-boundary, at least one character, and then another word boundary. You can use re.findall() to find all words in the string. re.compile() pre-compiles the regular expression so that it doesn’t have to be parsed from scratch for every line.
frozenset() is an efficient data structure that can answer the question “is the given word in the frozen set?” faster than is possible by scanning through a long list of keywords and trying every one of them.
#!/usr/bin/env python2.7
import re
RE_WORD = re.compile(r'\b[a-zA-Z]+\b')
keywords = frozenset(['foo', 'bar', 'joe', 'mauer'])
listOfStrings = ['I am frustrated', 'this task is foobar', 'mauer is awesome']
for i in listOfStrings:
for word in RE_WORD.findall(i):
if word in keywords:
print i
continue
A regex of the form r"(abc|ef|xxx)" will match with "abc", "ef", or "xxx". You can create this regex by using the string concatenation as below.
Note re.search returns None if no match is found.
import re
phrases = ['hello', 'hi', 'bye']
def match(text):
r = re.search(r'\b({})\b'.format("|".join(phrases)), text)
return r is not None
match("hi there, how are you?"), match("hithere, how are you?")
# (True, False)
One possible solution is to first split() the sentence into words, then strip() any punctuation marks and alike for each word and finally check if that word matches a word in the list. Actually you should not use a list but a Set which will enable lookups in constant (O(1)) time instead of linear (O(n)) time as is the case with lists.
phrases = ['hello', 'hi', 'bye']
phraseSet = set(phrases)
def match(text: str, word_set: set[str]) -> bool:
words = text.split(" ")
for word in words:
stripped = word.strip(".?!,:")
if stripped in word_set:
return True
return False
print(match("hi there, how are you?", phraseSet))
print(match("hithere, how are you?", phraseSet))
Obviously one could write the above solution in a more pythonic way.