计算两个词在一个句子中同时出现的频率
Count frequency of two words occuring together in a sentence
我有一个 pandas 数据框,其中一列中有词形化文本。
我想计算两个给定单词在同一个句子中一起出现的频率,并计算这些单词在文档中一起出现的次数。例如给定“我”和“有”,计算文档中“我”和“有”在同一个句子中一起出现的次数。
理想情况下,我想创建一个新的 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
这是伪代码,但可以采用任何语言:
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
}
您可以使用 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)
我有一个 pandas 数据框,其中一列中有词形化文本。
我想计算两个给定单词在同一个句子中一起出现的频率,并计算这些单词在文档中一起出现的次数。例如给定“我”和“有”,计算文档中“我”和“有”在同一个句子中一起出现的次数。
理想情况下,我想创建一个新的 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
这是伪代码,但可以采用任何语言:
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
}
您可以使用 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)