#python #regex #pandas #string #dataframe
#python #регулярное выражение #панды #строка #фрейм данных
Вопрос:
Я пытаюсь получить блоки текста (по 250 символов с каждой стороны) для каждого вхождения слова внутри dataset
. Когда я вызываю ту же логику кода в примере с игрушкой:
import re
list_one = ['as','the','word']
text = 'This is sample text to test if this pythonic '
'program can serve as an indexing platform for '
'finding words in a paragraph. It can give '
'values as to where the word is located with the '
'different examples as stated'
# find all occurances of the word 'as' in the above text
for i in list_one:
find_the_word = re.finditer(i, text)
for match in find_the_word:
print('start {}, end {}, search string '{}''.
format(match.start(), match.end(), match.group()))
код способен без проблем определять положение каждого вхождения каждого элемента списка. Однако, когда я пытаюсь применить ту же логику к 'apply'
фрейму данных с помощью метода, он возвращает ошибку TypeError: unhashable type: 'list'
Код:
import re
import pandas as pd
def find_text_blocks(text, unique_items):
'''
This function doesn't work as intended.
'''
empty_list = []
for i in unique_items:
find_the_word = re.finditer(i, text)
for match in find_the_word:
pos_all = match.start()
x = slice(pos_all-350, pos_all 350)
text_slice = text[x]
empty_list.append(text_slice)
return empty_list
dataset['text_blocks'] = dataset['text'].apply(find_text_blocks, unique_items = dataset['unique_terms'])
Каждая строка dataset['unique_items']
столбца содержит список, в то время как каждая строка dataset['text']
столбца содержит строки.
Приветствуются любые указания о том, как вернуть список строк в каждой строке dataset['text_blocks']
. Заранее спасибо 🙂
Ответ №1:
В вашей последней строке вашего кода используйте unique_items=dataset['unique_terms'][0]
вместо unique_items=dataset['unique_terms']
, и это будет работать.
Объяснение:
Сначала давайте построим набор данных:
dataset = pd.DataFrame({'text':[text] ,'unique_terms':[['as','the','word']]})
если мы перечислим этот столбец unique_terms
:
list(dataset['unique_terms'])
Out[3]: [['as', 'the', 'word']]
Это поможет нам понять, что в последней строке вашего кода вместо использования
unique_items = dataset['unique_terms']
мы должны использовать
unique_items=dataset['unique_terms'][0]
и это будет работать.
Наконец, полный код, который я тестировал, с изменением в последней строке:
import re
import pandas as pd
list_one = ['as', 'the', 'word']
text = 'This is sample text to test if this pythonic '
'program can serve as an indexing platform for '
'finding words in a paragraph. It can give '
'values as to where the word is located with the '
'different examples as stated'
dataset = pd.DataFrame({'text': [text], 'unique_terms': [list_one]})
def find_text_blocks(text, unique_items):
'''
This function doesn't work as intended.
'''
print(text, unique_items)
empty_list = []
for i in unique_items:
find_the_word = re.finditer(i, text)
for match in find_the_word:
pos_all = match.start()
x = slice(pos_all - 350, pos_all 350)
text_slice = text[x]
empty_list.append(text_slice)
print(empty_list)
return empty_list
dataset['text_blocks'] = dataset['text'].apply(find_text_blocks, unique_items=dataset['unique_terms'][0])
Теперь это работает.