Этот подход должен дать вам структуру, которую вы ищете, с подсчетами POS
, являющимися полным счетом этого тега в представленном корпусе.
ПРИМЕЧАНИЕ: The RETAIN_PUNCTUATION_FLAG
и RETAIN_CASE_FLAG
позволяют переключать поведение, чтобы либо убрать пунктуацию перед оценкой, либо сделать регистр единообразным, либо сохранить верхний / нижний регистр, либо просто выполнить оба действия.Здесь им обоим назначено False
, все слова будут обрабатываться в нижнем регистре, а все ASCII
знаки препинания будут удалены перед оценкой.
Я добавил word_list
и pos_list
для альтернативысписок.
from string import punctuation
RETAIN_PUNCTUATION_FLAG = False
RETAIN_CASE_FLAG = False
string = "DT The NN dog VB jumps DT the NN sofa. DT The NN cat VB pages DT the NN page."
punctuation_strip_table = str.maketrans('', '', punctuation)
if RETAIN_CASE_FLAG and RETAIN_PUNCTUATION_FLAG:
pass
elif RETAIN_CASE_FLAG and not RETAIN_PUNCTUATION_FLAG:
string = string.translate(punctuation_strip_table)
elif not RETAIN_CASE_FLAG and RETAIN_PUNCTUATION_FLAG:
string = string.casefold()
elif not RETAIN_CASE_FLAG and not RETAIN_PUNCTUATION_FLAG:
string = string.casefold().translate(punctuation_strip_table)
list_all = string.split(' ')
pos_word_pairs = set(zip(
list_all[0:][::2],
list_all[1:][::2]))
pos_list = {pos.upper(): {
'count': list_all.count(pos),
'words': [
word
for match_pos, word in pos_word_pairs
if match_pos == pos]
}
for pos in set(list_all[0:][::2])}
word_list = {word: {
'count': list_all.count(word),
'pos': [
pos.upper()
for pos, match_word in pos_word_pairs
if match_word == word]
}
for word in set(list_all[1:][::2])}
paired = {
word: {
pos.upper():
list_all.count(pos)}
for pos, word
in pos_word_pairs}
print('pos_list:', pos_list)
print()
print('word_list:', word_list)
print()
print('paired:',paired)
Вывод:
pos_list: {'VB': {'count': 2, 'words': ['pages', 'jumps']}, 'NN': {'count': 4, 'words': ['page', 'dog', 'sofa', 'cat']}, 'DT': {'count': 4, 'words': ['the']}}
word_list: {'dog': {'count': 1, 'pos': ['NN']}, 'cat': {'count': 1, 'pos': ['NN']}, 'jumps': {'count': 1, 'pos': ['VB']}, 'the': {'count': 4, 'pos': ['DT']}, 'page': {'count': 1, 'pos': ['NN']}, 'sofa': {'count': 1, 'pos': ['NN']}, 'pages': {'count': 1, 'pos': ['VB']}}
paired: {'pages': {'VB': 2}, 'jumps': {'VB': 2}, 'the': {'DT': 4}, 'page': {'NN': 4}, 'dog': {'NN': 4}, 'sofa': {'NN': 4}, 'cat': {'NN': 4}}