我编写了一个包含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应该是列表而不是字典
但我也尝试用列表替换它。它不会简单地取代。
与列表相关,下面将是代码:
contentText = [i for i in contentText if i not in remArticles]
的延续
最初我在尝试:
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'
答案 0 :(得分:3)
您的问题不明确,但如果您的目标是将字符串转换为列表,删除不需要的字词,然后将列表重新转换为字符串,那么您可以这样做:
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
答案 1 :(得分:0)
您的问题是您的地图包含按键内的空格。以下代码解决了您的问题:
[i for i in contentText if i not in map(lambda x: x.strip(), remArticles.keys())]