属性错误:"unicode"对象没有属性"remove"



我试图将字符串转换为单独的单词列表 - 除了字母之外什么都没有。但是,据我所知,unicode 导致了问题。

essay_text = ['This,', 'this,', 'this', 'and', 'that.']
def create_keywords(self):
    low_text = self.essay_text.lower()
    word_list = low_text.split()
    abcs = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'x', 'y', 'z']
    for n in word_list:
        for m in n:
            for l in abcs:
                if m!=l:
                    n.remove(m)
        self.keywords.setdefault(n, 0)
        self.keywords[n] = word_list.count(n)
        for m in bad_words:
            if n==m:
                del self.keywords[n]
    print self.keywords

我收到此错误:

AttributeError: 'unicode' object has no attribute 'remove'

我该如何解决这个问题?

更新:我不明白为什么我的字符串是 unicode。如果相关,下面是此模型所在的类:

class Essay(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    email = models.EmailField(max_length=100)
    essay_text = models.TextField()
    sources = models.TextField()
    def __unicode__(self):
         return self.title

为什么我的字符串是 unicode 格式的?

错误是明确的:n变量是一个字符串,没有remove的方法 - 这是因为字符串在 Python 中是不可变的。您必须创建一个没有要删除的字符的新字符串。

你的代码中有from __future__ import unicode_literals吗? 这将导致Python 2.X将'string'视为Unicode。

正如其他人所说,字符串是不可变的,也没有remove方法。

有几个模块可以大大简化您的目标:

import re
from collections import Counter
bad_words = ['and']
def create_keywords():
    essay_text = 'This, this, this and that.'
    # This regular expression finds consecutive strings of lowercase letters.
    # Counter counts each unique string and collects them in a dictionary.
    result = Counter(re.findall(r'[a-z]+',essay_text.lower()))
    for w in bad_words:
        result.pop(w)
    return dict(result) # return a plain dict instead of a Counter object.

输出:

>>> create_keywords()
{'this': 3, 'that': 1}

字符串是不可变的,这意味着它们不能更改。您真正需要做的就是在其位置创建一个仅包含字母的新字符串:

def just_letters(s):
    return ''.join(l for l in s if l in string.lowercase)
word_list = [just_letters(word) for word in word_list]

最新更新