简体   繁体   中英

Python List Comprehensions - Comparing with Dict

I write a code that has str data

def characters(self, content):
    self.contentText = content.split()
# self.contentText is List here

I am sending self.contentText list to another module as:

self.contentText = Formatter.formatter(self.contentText)

In this method, I am writing below code:

remArticles = remArticles = {' a ':'', ' the ':'', ' and ':'', ' an ':'', '&  nbsp;':''}

contentText = [i for i in contentText if i not in remArticles.keys()]

But it is not replacing. Is it that remArticles should be list and not dict

But I tried replacing it with list too. It wouldn't simply replace.

ofcourse with list, below will be the code:

  contentText = [i for i in contentText if i not in remArticles]

This is continuation from Accessing Python List Type

Initially I was trying:

for i in remArticles:
  print type(contentText) 
  print "1"
  contentText = contentText.replace(i, remArticles[i])
  print type(contentText) 

But that threw errors:

contentText = contentText.replace(i, remArticles[i])
AttributeError: 'list' object has no attribute 'replace'

Your question is not clear but if your goal is to convert a string to a list, remove unwanted words, and then turn the list back into a string, then you can do it like this:

def clean_string(s):
    words_to_remove = ['a', 'the', 'and', 'an', ' ']
    list_of_words = s.split()
    cleaned_list = [word for word in list_of_words if word not in words_to_remove]
    new_string = ' '.join(cleaned_list)
    return new_string

This is how you could do the same without converting to a list:

def clean_string(s):
    words_to_remove = ['a', 'the', 'and', 'an', ' ']
    for word in words_to_remove:
        s = s.replace(word, '')
    return s

And if you wanted more flexibility in removing some words but replacing others, you could do the following with a dictionary:

def clean_string(s):
    words_to_replace = {'a': '', 'the': '', 'and': '&', 'an': '', ' ': ' '}
    for old, new in words_to_replace.items():
        s = s.replace(old, new)
    return s

Your problem is that your map contains spaces within the keys. Following code solves your problem:

[i for i in contentText if i not in map(lambda x: x.strip(), remArticles.keys())]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM