python - 在句子级别找到每个单词的频率
问题描述
我有一个文本文件,其中的词被词性标记。该文件可以在这里看到。因此,每个单词及其标签都在一行中。句子由标签 SPACE 划分。我正在尝试创建一个程序,1)在句子级别找到频率高于 1 的单词,包含标签 NOUN、VERB、ADJ 和 ADV 2)打印找到的频率总和。我创建的程序计算频率不正确,因为它在前面的句子中添加了相同单词的频率。这不是我想要的。我想计算每个句子中项目(单词和标签)的频率,而不累积前面句子的频率。谁能帮我完成这项任务?到目前为止,我的代码如下:
while True:
try:
file_to_open =Path("Please, insert your file path: "))
with open(file_to_open,'r', encoding="utf-8") as f:
sentences = f.read()
break
except FileNotFoundError:
print("\nFile not found. Better try again")
except IsADirectoryError:
print("\nIncorrect Directory path.Try again")
units=sentences.split('<<SPACE>>')
print(len(units))
count={}
w=open('Alice_repetitions_sentence_AnaB.txt','w')
for sentence_num, unit in enumerate(units, 1):
lines=unit.split('\n')
total_count=len(lines)
for s in lines:
if s in count:
count[s]+=1
else:
count[s]=1
for key in count:
if 'VERB' in key and count[key] >1:
print(sentence_num,key, count[key])
elif 'NOUN' in key and count[key] >1:
print(sentence_num,key, count[key])
elif 'ADJ' in key and count[key] >1:
print(sentence_num,key, count[key])
elif 'ADV' in key and count[key] >1:
print(sentence_num,key, count[key])
我想要的输出应该是:
句子1:word1 - 4,word2 - 3,word3 - 8,依此类推..重复项目:3
句子 2:word1 - 4,word2 - 3,word3 - 8,word4-10 等等..重复项目:4。
句子3:word1 - 4,word2 - 3,word3 - 8,word4-10,word5-15等等......重复项目:5。
解决方案
from collections import Counter
def word_count(fname):
with open(fname) as f:
return Counter(f.read().split())
print("Number of words in the file :",word_count("test.txt"))
计算单词频率的简化版本
推荐阅读
- android - Developing with Cordova can I use Android Studio on Windows 10 and Ubuntu for Windows together?
- c - 关于局部变量的意外输出
- c - int 返回内存位置/地址吗?
- vue.js - 动态路线,但不是传统意义上的路线
- firebase - Firebase 中的“写”是什么?
- r - 使用 R 中的剪切函数剪切数据时显示空组
- ruby-on-rails - 如何在 reactJS 中处理重定向?
- javascript - 当我是参数化路由时如何重定向到原始路由
- c# - Rigidbody 和 Rigidbody2D 为什么条件运算符不起作用?
- php - 如何解决 laravel 中的 softdelete restore() 问题