【问题标题】:Using replace method in python 3.6在 python 3.6 中使用替换方法
【发布时间】:2017-11-25 21:46:23
【问题描述】:

我需要将“!@#$%^&*()\n{}[]()_-+=<>?\xa0;'/.,”替换为空白。我正在使用替换方法,但它似乎在 python 3.6 上已被弃用。 word_list = [] 是一个列表,其中包含从网页中提取的所有单词。然后clean_up_list 方法将清除符号并用空格替换它们。 我使用for 循环遍历符号的长度并将符号替换为空白。我用了 word = word.replace(symbols[i],"") ;有关如何使用 replace 方法的任何帮助,以便替换符号并打印单词之间没有符号。

错误:

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

我的代码:

url = urllib.request.urlopen("https://www.servicenow.com/solutions-by-category.html").read()
word_list = []
soup = bs.BeautifulSoup(url,'lxml')
word_list.append([element.get_text() for element in soup.select('a')])
print(word_list)

def clean_up_list(word_list):
    clean_word_list = []
    for word in word_list:
        symbols = "!@#$%^&*()\n{}[]()_-+=<>?\xa0;'/.,"
        for i in range(0,len(symbols)):

            word  = word.replace(symbols[i],"")
            #print(type(word))

                #print(type(word))
                #word.replace(symbols[i]," ")
        if(len(word) > 0):
            #print(word)
            clean_word_list.append(word)

【问题讨论】:

标签: python replace python-3.6


【解决方案1】:

这里有两个错误:首先你不是构造了一个字符串列表,而是一个字符串列表的列表。这一行:

word_list.append([element.get_text() for element in soup.select('a')])

应该是:

word_list.<b>extend</b>([element.get_text() for element in soup.select('a')])

此外,您不能在列表中直接调用replace (它不是list 对象的方法)。每个条目都需要这样做。

接下来,您还需要(正确地)指定replace(..),然后为symbols 字符串中的每个字符调用replace(..)。这当然是低效的。但是,您可以为此使用 translate(..)

所以你可以用列表理解替换整个for循环:

symbols = "!@#$%^&*()\n{}[]()_-+=<>?\xa0;'/.,"
clean_word_list = [word.translate(None,symbols) for word in word_list]

【讨论】:

  • 它仍然不会清理符号。需要用正则表达式检查。
  • @Shishir13:请提供样品word_list
【解决方案2】:

尝试将单词显式转换为字符串,因为您收到的错误代码提到该对象是“列表”而不是字符串,并且无法在列表上调用替换方法。例如(注意倒数第二行):

def clean_up_list(word_list):
clean_word_list = []
for word in word_list:
    word = str(word)
    symbols = "!@#$%^&*()\n{}[]()_-+=<>?\xa0;'/.,"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    • 2017-08-02
    相关资源
    最近更新 更多