【发布时间】:2014-05-07 16:59:13
【问题描述】:
我正在尝试编写一个函数来清理 URL(将它们去除“www.”、“http://”等任何内容)以创建一个可以按字母顺序排序的列表。
我试图通过创建一个类来做到这一点,该类包括一个方法来检测我想从 URL 字符串中删除的术语,并将其删除。我苦苦挣扎的一点是,我想将修改后的 URL 添加到一个名为 new_strings 的新列表中,然后在我以不同的期限第二次调用该方法时使用该新列表,这样我就可以一步一步地可以从 URL 字符串中删除所有不需要的元素。
由于某种原因,我当前的代码返回一个空列表,我也很难理解是否应该将new_strings 传递给__init__?我想我对全局变量和局部变量有点困惑,非常感谢一些帮助和解释。 :)
谢谢!代码如下。
class URL_Cleaner(object):
def __init__(self, old_strings, new_strings, term):
self.old_strings = old_strings
self.new_strings = new_strings
self.term = term
new_strings = []
def delete_term(self, new_strings):
for self.string in self.old_strings:
if self.term in string:
new_string = string.replace(term, "")
self.new_strings.append(new_string)
else:
self.new_strings.append(string)
return self.new_strings
print "\n" .join(new_strings) #for checking; will be removed later
strings = ["www.google.com", "http://www.google.com", "https://www.google.com"]
new_strings = []
www = URL_Cleaner(strings, new_strings, "www.")
【问题讨论】:
-
Class
__init__()方法不返回任何内容,它们只是初始化第一个参数,通常命名为self的类实例。