首页 > 解决方案 > 使用python查找字符串中连接单词的出现

问题描述

我有一个文本,其中所有单词都标有“词性”标签。这里的文本示例:

什么/名词可以/动词发生/动词下一个/ADJ ?/PUNCT

我需要找到所有出现的情况,其中有一个/PUNCTNOUN或者PRON-PROPN并且还计算最常出现的情况。

因此,其中一个答案将如下所示: ?/PUNCT What/NOUN./PUNCT What/NOUN

进一步关于“交易”一词出现了 6 次,我需要通过代码显示。

我不允许使用 NLTK,只能使用 Collections。

尝试了几种不同的东西,但真的不知道在这里做什么。我想我需要使用 defaultdict,然后以某种方式执行一个 while 循环,这给了我一个带有正确连接词的列表。

标签: python

解决方案


这是一个测试程序,可以满足您的需求。

它首先用空格分割长字符串,' '从而创建单词/类元素列表。然后 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()

推荐阅读