我有一个文本,其中所有单词都标有“词性”标签。这里的文字示例:
什么/ NOUN可以/ VERB发生/ VERB next / ADJ?/ PUNCT
我需要找到所有出现/PUNCT
,然后是NOUN
,PRON
或PROPN
的事件 - 并且还计算最常出现的那个。
因此,其中一个答案将如下所示:?/PUNCT What/NOUN
或./PUNCT What/NOUN
此外,“Deal”这个词出现了6次,我需要通过代码来显示。
我不允许使用NLTK,只允许使用集合。
尝试了几个不同的东西,但不知道该怎么做。我想我需要使用defaultdict,然后以某种方式做一个while循环,这给了我一个带有正确连接词的列表。
这是一个测试程序,可以满足您的需求。
它首先用空格' '
分割长字符串,它创建一个单词/类元素列表。然后for循环检查PUNCT后跟NOUN,PRON或PROPN的组合是否发生并将其保存到列表中。
代码如下:
from collections import Counter
string = "What/NOUN could/VERB happen/VERB next/ADJ ?/PUNCT What/NOUN could/VERB happen/VERB next/ADJ ?/PUNCT"
words = string.split(' ')
found = []
for n, (first, second) in enumerate(zip(words[:-1], words[1:])):
first_class = first.split('/')[1]
second_class = second.split('/')[1]
if first_class == 'PUNCT' and second_class in ["NOUN", "PRON", "PROPN"]:
print(f"Found occurence at data list index {n} and {n+1} with {first_class}, {second_class}")
found.append(f'{words[n]} {words[n+1]}')
计算单词:
words_only = [i.split('/')[0] for i in words]
word_counts = Counter(words_only).most_common()