【问题标题】:Find the frequency of each word at the sentence level在句子级别找到每个单词的频率
【发布时间】:2021-02-19 16:27:56
【问题描述】:

我有一个文本文件,其中的词被标记为词性。该文件可见here。因此,每个单词及其标签都在一行中。句子由标签 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.

【问题讨论】:

  • 编写一个函数,它将确定并返回您传递的任何字符串的 frequencies,然后只需将 sentences 传递给函数并累积返回值。

标签: python text frequency


【解决方案1】:
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"))

统计词频的简化版

【讨论】:

  • 我想分别统计每个句子的词频。
  • 你有什么独特的指示来识别句子吗?
  • 是的,正如我在解释我的问题时所说的那样。句子在文件中由标签 > 分隔。这已添加到我的代码中。 sentence.split('>')
猜你喜欢
  • 2012-10-10
  • 2014-03-13
  • 2019-02-20
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多