【问题标题】:custom word removal from a list in python从python中的列表中删除自定义单词
【发布时间】:2021-05-10 22:25:20
【问题描述】:

我正在编写一个函数来执行自定义单词删除、词干提取(获取单词的根形式),然后是 tf-idf。

我的函数输入数据是一个列表。如果我尝试在单个列表上进行自定义单词删除,那是可行的,但是当我将它组合到函数中时,我得到一个属性错误:

AttributeError: 'list' 对象没有属性 'lower'

这是我的代码:

def tfidf_kw(K):    
    # Select docs in cluster K
    docs = np.array(mydata2)[km_r3.labels_==K]

    ps= PorterStemmer()
    stem_docs = []
    for doc in docs:
        keep_tokens = []
        
        for token in doc.split(' '):
            #custom stopword removal
            my_list = ['model', 'models', 'modeling', 'modelling', 'python', 
           'train','training', 'trains', 'trained','test','testing', 'tests','tested']
            
            token  = [sub_token for sub_token in list(doc) if sub_token not in my_list]

            stem_token=ps.stem(token)
            keep_tokens.append(stem_token)

        keep_tokens =' '.join(keep_tokens)
        stem_docs.append(keep_tokens)

        return(keep_tokens)

更多代码适用于 tf-idf,它有效。这是我需要帮助的地方,以了解我做错了什么?

token  = [sub_token for sub_token in list(doc) if sub_token not in my_list]

这是完整的错误:

AttributeError  Traceback (most recent call last)
<ipython-input-154-528a540678b0> in <module>
     49     #return(sorted_df)
     50 
---> 51 tfidf_kw(0)

<ipython-input-154-528a540678b0> in tfidf_kw(K)
     20 
     21 
---> 22             stem_token=ps.stem(token)
     23             keep_tokens.append(stem_token)
     24 

~/opt/anaconda3/lib/python3.8/site-packages/nltk/stem/porter.py in stem(self, word)
    650 
    651     def stem(self, word):
--> 652         stem = word.lower()
    653 
    654         if self.mode == self.NLTK_EXTENSIONS and word in self.pool:

AttributeError: 'list' object has no attribute 'lower'

在第 51 行,上面写着 tfidf_kw(0),这就是我检查函数 k=0 的地方。

【问题讨论】:

    标签: python list function stop-words


    【解决方案1】:

    显然ps.stem 方法需要一个单词(字符串)作为参数,但您传递的是字符串列表。

    由于您已经在 for token in doc.split(' ') 循环中,因此另外使用列表理解 [... for sub_token in list(doc) ...] 对我来说似乎没有意义。

    如果您的目标是跳过my_list 中的那些标记,大概您想像这样编写for token in doc.split(' ') 循环:

    for token in doc.split(' '):
        my_list = ['model', 'models', 'modeling', 'modelling', 'python', 
       'train','training', 'trains', 'trained','test','testing', 'tests','tested']
    
        if token in my_list:
            continue
        
        stem_token=ps.stem(token)
        keep_tokens.append(stem_token)
    

    这里,如果tokenmy_list 中的单词之一,continue 语句将跳过当前迭代的其余部分,循环继续下一个token

    【讨论】:

    • 很棒,但是,对于 k=0,我希望有 124 行,但是当我检查 keep_tokens 变量时,我只看到 1 行。即上述标记化仅应用于 1 行。
    • 我注意到你在循环中有return 行——你应该把它移出循环,这可能解释了这种行为。您可能还应该返回 stem_docs 而不是 keep_tokens
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    • 2021-12-29
    • 2018-12-28
    • 2018-09-28
    • 2022-07-06
    • 1970-01-01
    相关资源
    最近更新 更多