Po pierwsze, możesz przekonwertować wszystko na małe litery, usunąć znaki interpunkcyjne i białe znaki, a następnie przekonwertować wynik na zestaw słów.
import string
df['words'] = [set(words) for words in
df['col_name']
.str.lower()
.str.replace('[{0}]*'.format(string.punctuation), '')
.str.strip()
.str.split()
]
>>> df
col_name words
0 This is Donald. {this, is, donald}
1 His hands are so small {small, his, so, are, hands}
2 Why are his fingers so short? {short, fingers, his, so, are, why}
Można teraz używać logiczną indeksowanie aby sprawdzić, czy wszystkie słowa są swój cel w tych nowych zestawów słownych.
target_words = ['is', 'small']
# Convert target words to lower case just to be safe.
target_words = [word.lower() for word in target_words]
df['match'] = df.words.apply(lambda words: all(target_word in words
for target_word in target_words))
print(df)
# Output:
# col_name words match
# 0 This is Donald. {this, is, donald} False
# 1 His hands are so small {small, his, so, are, hands} False
# 2 Why are his fingers so short? {short, fingers, his, so, are, why} False
target_words = ['so', 'small']
target_words = [word.lower() for word in target_words]
df['match'] = df.words.apply(lambda words: all(target_word in words
for target_word in target_words))
print(df)
# Output:
# Output:
# col_name words match
# 0 This is Donald. {this, is, donald} False
# 1 His hands are so small {small, his, so, are, hands} True
# 2 Why are his fingers so short? {short, fingers, his, so, are, why} False
aby wyodrębnić wiersze pasujące:
>>> df.loc[df.match, 'col_name']
# Output:
# 1 His hands are so small
# Name: col_name, dtype: object
, aby to wszystko w jednym rachunku przy użyciu logiczną indeksowania:
df.loc[[all(target_word in word_set for target_word in target_words)
for word_set in (set(words) for words in
df['col_name']
.str.lower()
.str.replace('[{0}]*'.format(string.punctuation), '')
.str.strip()
.str.split())], :]
Dziękuję. Odbiłem twój punkt/b -> \ b. Nadal chcesz poczekać kilka kolejnych dni, aby sprawdzić, czy jest jakiś inny sposób na złapanie całego słowa. – Aaron
stycznie, musiałem dodać 'r' przed ciągiem, aby uruchomić go: każdy wie, dlaczego? Nie znalazłem żadnego odniesienia do niego .. – mccc
Cóż, najwyraźniej '' char powoduje, że jest ono domyślnie w wyrażeniu regularnym, natomiast '\ b' nie .. – mccc