繁体   English   中英

Python列表推导-与Dict比较

[英]Python List Comprehensions - Comparing with Dict

我写了一个有str数据的代码

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

我将self.contentText列表发送到另一个模块为:

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

在这种方法中,我正在编写以下代码:

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

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

但这并不能替代。 是remArticles应该列出而不是dict

但是我也尝试用list代替它。 它不会简单地替换。

当然带有列表,下面是代码:

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

这是从访问Python列表类型的延续

最初我在尝试:

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

但这引发了错误:

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

您的问题尚不清楚,但是如果您的目标是将字符串转换为列表,删除不需要的单词,然后将列表转换回字符串,则可以执行以下操作:

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

这是您无需转换为列表即可执行的操作:

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

而且,如果您希望在删除某些单词而替换其他单词时更加灵活,则可以使用字典执行以下操作:

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

您的问题是您的地图在键中包含空格。 以下代码解决了您的问题:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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