计算句子中两个单词同时出现的频率

2024-03-29 12:37:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据框,在其中的一列中有柠檬化的文本

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

理想情况下,我希望创建一个新的数据框架,其中一列中我将两个单词放在一起,另一列中两个单词一起出现在一个句子中,第三列中是原始文本

我的结果应该是:

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 

Tags: 数据in文档文本have情况单词次数
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)

这是伪代码,但可用于任何语言:

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" )

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

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
}

相关问题 更多 >