I need to replace the POStags (parts of speech) by other POStags.
# From
"When_WRB it_PRP 's_VBZ time_NN for_IN their_PRP$ ..."
# To
"When_ADV it_PRON 's_VERB time_NOUN for_ADP their_PRON ..."
Here is an extract of the universal dependency POS file that does the mapping between the POStags I have and the POStags I want.
IN ADP
NN NOUN
PRP PRON
PRP$ PRON
VBZ VERB
WRB ADV
I can load the mapping into a python dict (with only relevant keys for the example) :
{'VERB': ['MD', 'VB', 'VBZ', 'VBP', 'VBD', 'VBN', 'VBG'],
'NOUN': ['NN', 'NNS', 'NNP', 'NNPS'], 'ADP': ['IN'],
'PRON': ['PRP', 'PRP$', 'WP', 'WP$'],
'ADV': ['RB', 'RBR', 'RBS', 'WRB'],
}
The dictionary is well-formed. I would like to replace each values in the list, by the key. So MD would be VERB and NNS would be NOUN.
For the moment, i have this code :
import re
# Load the POStag mapping :
with open('POSfile', 'r', encoding='utf-8') as universal:
dict_pos = {}
for line in universal.readlines():
result = re.match('(.+)\s+(.+)', line.strip())
if result.group(2) not in dict_pos:
dict_pos[result.group(2)] = []
dict_pos[result.group(2)].append(result.group(1))
sentence = "When_WRB it_PRP 's_VBZ time_NN for_IN their_PRP$"
# For each target POStag
for key, value in dict_pos.items():
# Replace any of the source POStag by the target POStag
pattern = re.compile('|'.join(value))
if re.match(pattern, sentence):
line = re.sub(pattern, key, sentence)
I'm struggling with list values like {'DET': ['DT', 'PDT', 'WDT']}.
How to replace one of the value element by the key (DET) here ?