python - 使用python查找字符串中连接单词的出现
问题描述
我有一个文本,其中所有单词都标有“词性”标签。这里的文本示例:
什么/名词可以/动词发生/动词下一个/ADJ ?/PUNCT
我需要找到所有出现的情况,其中有一个/PUNCT
,NOUN
或者PRON
-PROPN
并且还计算最常出现的情况。
因此,其中一个答案将如下所示:
?/PUNCT What/NOUN
或./PUNCT What/NOUN
进一步关于“交易”一词出现了 6 次,我需要通过代码显示。
我不允许使用 NLTK,只能使用 Collections。
尝试了几种不同的东西,但真的不知道在这里做什么。我想我需要使用 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()
推荐阅读
- python - 如何通过使用re python忽略特定字符从字符串中搜索特定单词
- facebook-javascript-sdk - 如何使用带有 javascript sdk 的共享对话框在 fb 时间轴上发布视频?
- reactjs - 将反应项目添加到反应项目?或一页?
- angular - 海量组件订阅还是单次订阅+导出数据?
- python - 通过对像素求和来重新缩放矩阵
- ruby-on-rails - 在 Sidekiq 作业中使用 Kaminari 渲染分页
- html - Asp.net MVC 导航栏
- mysql - MySQL 使用 GROUP BY 时的慢查询
- wordpress-gutenberg - 将多个 Gutenberg 块放在一个文件中 - 块数是否有限制?最后添加的一个不在插入器对话框中
- linear-programming - GLPK 输出格式