簡體   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