AttributeError:“unicode”对象没有“remove”属性

2024-05-18 10:53:25 发布

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

我正试着把一个字符串变成一个单独的单词列表——除了字母什么都没有。然而,据我所知,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格式的?


Tags: 字符串textinselfformodelsdefunicode
3条回答

你的代码中有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]

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

相关问题 更多 >