Вы можете сделать это, используя DataFrame.apply
и регулярное выражение.
import re
import pandas as pd
data = {
'Author': ['Smith', 'Green'],
'Title' : ['ABC', 'XYZ'],
'Text' : [
["This is the first sentence", "This is the second sentence"],
["Also a sentence", "And the second sentence"]
]
}
df = pd.DataFrame(data)
tokens = [
'first',
'second',
'th'
]
def find_token(text_list, re_pattern):
result = [
text
for text in text_list
if re.search(re_pattern, text.lower())
]
if result:
return result
return
for token in tokens:
re_pattern = re.compile(fr'(^|\s){token}($|\s)')
df[token] = df['Text'].apply(lambda x: find_token(x, re_pattern))
соответствует совпадению с токеном word
.
Таким образом, должен быть пробел или начало / конец предложения.
re.compile(r'(^|\s)')
означает пробел или начало.
re.compile(r'($|\s)')
означает пробел или конец.
Если вы используете 'th' в качестве токена, результат будет None
.
Используйте токены как ['first', 'second', 'th'], результат будет следующим.
Author Title Text \
0 Smith ABC [This is the first sentence, This is the secon...
1 Green XYZ [Also a sentence, And the second sentence]
first second th
0 [This is the first sentence] [This is the second sentence] None
1 None [And the second sentence] None