Python 是否有一个函数允许我确定文本是否涉及预定义的主题?

Python 是否有一个函数允许我确定文本是否涉及预定义的主题?,python,nlp,nltk,analysis,Python,Nlp,Nltk,Analysis,我想写主题列表来检查评论是否涉及某个定义的主题。对我来说,重要的是自己编写主题列表,而不是使用主题建模来寻找可能的主题 我以为这叫做字典分析,但我什么也找不到 我有一个包含亚马逊评论的数据框架: df = pd.DataFrame({'User': ['UserA', 'UserB','UserC'], 'text': ['Example text where he talks about a phone and his charging cable', 'Example text wher

我想写主题列表来检查评论是否涉及某个定义的主题。对我来说,重要的是自己编写主题列表,而不是使用主题建模来寻找可能的主题

我以为这叫做字典分析,但我什么也找不到

我有一个包含亚马逊评论的数据框架:

df = pd.DataFrame({'User': ['UserA', 'UserB','UserC'], 
'text': ['Example text where he talks about a phone and his charging cable',
 'Example text where he talks about a car with some wheels',
 'Example text where he talks about a plane']})
现在我想定义主题列表:

phone = ['phone', 'cable', 'charge', 'charging', 'call', 'telephone']
car = ['car', 'wheel','steering', 'seat','roof','other car related words']
plane = ['plane', 'wings', 'turbine', 'fly']
该方法的结果应为第一次审查的“电话”主题的3/12(审查中有12个单词的主题列表中的3个单词),其他两个主题的0

第二次审查的结果是“汽车”主题为2/11,其他主题为0,第三次审查的结果是“飞机”主题为1/8,其他主题为0

结果如下:

phone_results = [0.25, 0, 0]
car_results = [0, 0.18181818182, 0]
plane_results = [0, 0, 0.125]
当然,我只会使用小写的评论词干,这样可以更容易地定义主题,但现在不应该担心这一点

这有什么方法吗?还是我必须写一个?
提前谢谢你

您可以使用RASA-NLU意向分类预训练模型

NLP可以非常深入,但对于已知单词的比例,您可能可以做一些更基本的事情。例如:

word_map = {
    'phone': ['phone', 'cable', 'charge', 'charging', 'call', 'telephone'],
    'car': ['car', 'wheels','steering', 'seat','roof','other car related words'],
    'plane': ['plane', 'wings', 'turbine', 'fly']
}
sentences = [
     'Example text where he talks about a phone and his charging cable',
     'Example text where he talks about a car with some wheels',
     'Example text where he talks about a plane'
]

for sentence in sentences:
    print '==== %s ==== ' % sentence
    words = sentence.split()
    for prefix in word_map:
        match_score = 0
        for word in words:
            if word in word_map[prefix]:
                match_score += 1
        print 'Prefix: %s | MatchScore: %.2fs' % (prefix, float(match_score)/len(words)) 
你会得到这样的结果:

==== Example text where he talks about a phone and his charging cable ==== 
Prefix: phone | MatchScore: 0.25s
Prefix: plane | MatchScore: 0.00s
Prefix: car | MatchScore: 0.00s
==== Example text where he talks about a car with some wheels ==== 
Prefix: phone | MatchScore: 0.00s
Prefix: plane | MatchScore: 0.00s
Prefix: car | MatchScore: 0.18s
==== Example text where he talks about a plane ==== 
Prefix: phone | MatchScore: 0.00s
Prefix: plane | MatchScore: 0.12s
Prefix: car | MatchScore: 0.00s
当然,这是一个基本的例子,单词有时不以空格结尾——可以是逗号、句点等,所以你应该考虑到这一点。还有我可以“给某人打电话”或“打电话”,或“打电话”的时态,但我们也不想让“拼音”这样的词混淆起来。因此,在边缘情况下,它变得相当棘手,但对于一个非常基本的工作(!)示例,我想看看您是否可以在python中不使用自然语言库就完成它。最后,如果它不符合您的用例,您可以开始测试它们


除此之外,您还可以查看类似或的内容。

我想我会回馈社区,并发布基于@David542答案的完成代码:

import pandas as pd
import numpy as np 
import re

i=0
#Iterates through the reviews
total_length = len(sentences)
print("Process started:")
s = 1
for sentence in sentences:


    #Splits a review text into single words
    words = sentence.split()
    previous_word = ""
    #Iterates through the topics, each is one column in a table
    for column in dictio:
        #Saves the topic words in the pattern list
        pattern = list(dictio[column])
        #remove nan values
        clean_pattern = [x for x in pattern if str(x) != 'nan']
        match_score = 0
        #iterates through each entry of the topic list
        for search_words in clean_pattern:
            #iterates through each word of the review
            for word in words:
                #when two consecutive words are searched for the first if statement gets activated
                if len(search_words.split())>1:

                    pattern2 = r"( "+re.escape(search_words.split()[0])+r"([a-z]+|) "+re.escape(search_words.split()[1])+r"([a-z]+|))"
                    #the spaces are important so bedtime doesnt match time
                    if re.search(pattern2, " "+previous_word+" "+word, re.IGNORECASE):
                        match_score +=1
                        #print(pattern2, " match ", previous_word," ", word)

                if len(search_words.split())==1:

                    pattern1 = r" "+re.escape(search_words)+r"([a-z]+|)"
                    if re.search(pattern1, " "+word, re.IGNORECASE):
                        match_score +=1
                        #print(pattern1, " match ", word)

                #saves the word for the next iteration to be used as the previous word
                previous_word = word


        result=0       
        if match_score > 0:
            result = 1
        df.at[i, column] = int(result)
    i+=1
    #status bar
    factor = round(s/total_length,4)
    if factor%0.05 == 0:
        print("Status: "+str(factor*100)+"%")
    s+=1

我要分析的文本在字符串列表中
句子
。我想在文本中查找的主题位于dataFrame
dictio
中。该主题以主题名称开头,并有多行搜索词。这些分析提取一个或两个连续的单词,并在每个字符串中查找具有可变结尾的单词。如果正则表达式与原始数据框
df
匹配,则在分配给主题的列的相应行中获得一个“1”。在我的问题中,我没有计算单词的百分比,因为我发现它不会给我的分析增加价值。应该删除字符串中的标点符号,但不需要词干。如果您有具体问题,请发表意见,我将编辑此代码或回答您的意见。

熊猫本身无法做到这一点。要构建这样的东西,您需要这样的东西。您知道NLTK是否有这样的方法吗?我查看了文档,但没有发现任何东西。你应该看看BLEU Scoringtanks,这实际上与我需要的非常相似。但是,我能够调整已接受的答案以满足我的需要:)