[英]Find occurrences of connecting words in a string with python
我有一个文本,其中所有单词都标有“词性”标签。 这里的文字示例:
什么/ NOUN可以/ VERB发生/ VERB next / ADJ?/ PUNCT
我需要找到所有出现的地方有一个/PUNCT
后接NOUN
, PRON
或PROPN
-也算其中一个出现得最频繁。
所以其中一个答案如下所示: ?/PUNCT What/NOUN
./PUNCT What/NOUN
或./PUNCT What/NOUN
此外,“交易”一词出现了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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.