一个简单的计数器功能将执行您想要的!
输入:
df = pd.DataFrame({'POS':['(communications, NNS), (between,IN), (the, DT), (Principal, NNP), (and, CC), (the, DT), (Contractor, NNP), (shall, MD), (be,VB), (in, DT), (the, DT), (English, JJ), (language, NN)', '(Contractor, NNP), (shall, MD), (be,VB), (communications, NNS), (between,IN), (the, DT), (Principal, NNP), (and, CC), (the, DT), (Contractor, NNP), (shall, MD), (be,VB), (in, DT), (the, DT), (English, JJ), (language, NN)', '(and, CC), (the, DT)']})
功能:
def counter(pos):
words, tags = [], []
for item in pos.split('), ('):
temp = item.strip(' )(')
word, tag = temp.split(',')[0], temp.split(',')[-1].strip()
words.append(word); tags.append(tag)
length = len(tags)
if length<3:
return 0
count = 0
for idx in range(length):
if tags[idx:idx+3]==['NNP', 'MD', 'VB']:
count+=1
return count
输出:
df['occ'] = df['POS'].apply(counter)
df
POS occ
0 (communications, NNS), (between,IN), (the, DT)... 1
1 (Contractor, NNP), (shall, MD), (be,VB), (comm... 2
2 (and, CC), (the, DT) 0