Python语言检测代码的优化与词法化

2024-04-28 07:25:02 发布

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

我有一个JSON格式的amazon用户评论数据,我将其导入到pandas dataframe中,并使用它来训练文本分类模型。我试图在使用这些数据训练模型之前对用户评论文本进行预处理。我有两个问题:

1)我用Python中的Textblob库编写了一个代码来检测它的语言,它运行良好,但需要花费大量的时间。请告诉我是否有一个最佳的方法。我正在使用python中的Textblob库,代码是:

    from textblob import TextBlob
    def detect_language(text):
        if len(text)>3:
            r=TextBlob(text)
            lang = r.detect_language()
            return lang
    dataset['language']=dataset.reviewText.apply(lambda x: detect_language(x))

2)在训练模型之前,我想把我的词词义化。但是,由于NLTK中的柠檬化将正常工作,如果我们的词性标记有单词,我尝试如下,但有一些错误:

^{pr2}$

在这里,我将pos标记为:

    [('my', 'PRP$'), ('name', 'NN'), ('is', 'VBZ'), ('shubham', 'JJ')]

在进行柠檬化时,我得到的错误是:

    AttributeError: 'tuple' object has no attribute 'endswith'

你能建议一个有效的方法来执行柠檬化。 以下是我正在执行语言检测和柠檬化的示例数据:

    overall reviewText
        5   Not much to write about here, but it does exac...
        5   The product does exactly as it should and is q...
        5   The primary job of this device is to block the...
        5   Nice windscreen protects my MXL mic and preven...
        5   This pop filter is great. It looks and perform...

Tags: and数据方法代码text用户模型文本
1条回答
网友
1楼 · 发布于 2024-04-28 07:25:02

TL;DR

from nltk import pos_tag, word_tokenize
from nltk.stem import WordNetLemmatizer

wnl = WordNetLemmatizer()

def penn2morphy(penntag):
    """ Converts Penn Treebank tags to WordNet. """
    morphy_tag = {'NN':'n', 'JJ':'a',
                  'VB':'v', 'RB':'r'}
    try:
        return morphy_tag[penntag[:2]]
    except:
        return 'n' 

def lemmatize_sent(text): 
    # Text input is string, returns lowercased strings.
    return [wnl.lemmatize(word.lower(), pos=penn2morphy(tag)) 
            for word, tag in pos_tag(word_tokenize(text))]

对字符串的数据帧列进行柠檬化。在

^{pr2}$

很长时间内

https://www.kaggle.com/alvations/basic-nlp-with-nltk

相关问题 更多 >