【问题标题】:Count frequency of two words occuring together in a sentence计算句子中两个单词同时出现的频率
【发布时间】:2020-08-14 14:38:12
【问题描述】:

我有一个 pandas 数据框,其中一列中有词形还原的文本。

我想计算两个给定单词在同一个句子中一起出现的频率,并计算这些单词在文档中一起出现的次数。例如给定“I”和“have”,计算文档中“I”和“have”在同一个句子中同时出现的次数。

理想情况下,我想创建一个新的 DataFrame,其结果在一列中我将两个单词放在一起,在另一列中两个单词一起出现在一个句子中,在第三列中显示原始文本。

我的结果需要类似于:

text, given_words, frequency_in_sentence
text1 | "I have " | 2 times in same sentence 
text2 | "I have " | 3 times in same sentence 
text3 | "I have " | 1 times in same sentence 

【问题讨论】:

标签: python nlp nltk token spacy


【解决方案1】:

这是伪代码,但可以被任何语言采用:

word1="whatever"
word2="yes"


for (text:texts)
     sentances=text.getSentances()

count=0
for (sentance:sentances)
     if ( sentance.contains(word1,word2) )
          count++

print ( "text " + text.name + " " + word1 + " " + word2 + " appears in same sentances " + count + " times" )

那么你需要像下面这样的“句子”方法

boolean contains (String ... words){
     int args = words.length;     
     int matchCount=0;
     for (word : words)
           if (this.text.match(word)
                 matchCount++ && continue


     if matchCount==args
           return true


     return false
}

【讨论】:

  • for 读起来像“for each”,并假设您可以创建对象或某种实体来表示您尝试使用的概念。 ... 表示“可变参数”,意味着它们作为字符串数组传递给函数,可以有 0 到可以存储在数组中的最大项目数
  • 你会如何在 Python 中做到这一点?
  • 你是在问我如何运行python脚本或解决问题吗???假设您可以在 python 中运行一个简单的 hello world,只需将语法更改为 py 并将其放入文件 myprog.py 并从命令行通过python 运行它?或者无论如何你已经设置好了。请记住,这是 PSEUDO 代码,因此您需要对其进行修改才能使其正常工作
  • 这是对搭配的分析,使用nltk你可以毫不费力地做到这一点。
【解决方案2】:

您可以使用 count 并通过数据框上的应用函数来使用它:

def count(sentence, pattern):
    """ count pattern occurence """
    return word.count(sentence)

df['frequency_in_sentence'] = df.apply(lambda row:count(row['text'], row['given_words']), axis = 1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 2023-03-22
    相关资源
    最近更新 更多