是否有更好/更加蟒蛇化的方式来做到这一点?

时间:2010-09-15 13:52:03

标签: python optimization string random

我在新工作中一直在教自己Python,并且非常喜欢这门语言。我写了一个简短的类来做一些基本的数据操作,我对此非常有信心。

但是我的结构化/模块化编程时代的旧习惯很难打破,我知道必须有更好的方法来写这个。所以,我想知道是否有人想看看以下内容,并建议一些可能的改进,或者让我找到一个可以帮助我自己发现这些的资源。

快速说明:RandomItems根类是由其他人编写的,我仍然围绕着itertools库。此外,这不是整个模块 - 只是我正在研究的课程,而且它是先决条件。

您怎么看?

import itertools
import urllib2
import random
import string

class RandomItems(object):
    """This is the root class for the randomizer subclasses. These
        are used to generate arbitrary content for each of the fields
        in a csv file data row. The purpose is to automatically generate
        content that can be used as functional testing fixture data.
    """
    def __iter__(self):
        while True:
            yield self.next()

    def slice(self, times):
        return itertools.islice(self, times)

class RandomWords(RandomItems):
    """Obtain a list of random real words from the internet, place them
        in an iterable list object, and provide a method for retrieving
        a subset of length 1-n, of random words from the root list.
    """
    def __init__(self):
        urls = [
            "http://dictionary-thesaurus.com/wordlists/Nouns%285,449%29.txt",
            "http://dictionary-thesaurus.com/wordlists/Verbs%284,874%29.txt",
            "http://dictionary-thesaurus.com/wordlists/Adjectives%2850%29.txt",
            "http://dictionary-thesaurus.com/wordlists/Adjectives%28929%29.txt",
            "http://dictionary-thesaurus.com/wordlists/DescriptiveActionWords%2835%29.txt",
            "http://dictionary-thesaurus.com/wordlists/WordsThatDescribe%2886%29.txt",
            "http://dictionary-thesaurus.com/wordlists/DescriptiveWords%2886%29.txt",
            "http://dictionary-thesaurus.com/wordlists/WordsFunToUse%28100%29.txt",
            "http://dictionary-thesaurus.com/wordlists/Materials%2847%29.txt",
            "http://dictionary-thesaurus.com/wordlists/NewsSubjects%28197%29.txt",
            "http://dictionary-thesaurus.com/wordlists/Skills%28341%29.txt",
            "http://dictionary-thesaurus.com/wordlists/TechnicalManualWords%281495%29.txt",
            "http://dictionary-thesaurus.com/wordlists/GRE_WordList%281264%29.txt"
        ]
        self._words = []
        for url in urls:
            urlresp = urllib2.urlopen(urllib2.Request(url))
            self._words.extend([word for word in urlresp.read().split("\r\n")])
        self._words = list(set(self._words)) # Removes duplicates
        self._words.sort() # sorts the list

    def next(self):
        """Return a single random word from the list
        """
        return random.choice(self._words)

    def get(self):
        """Return the entire list, if needed.
        """
        return self._words

    def wordcount(self):
        """Return the total number of words in the list
        """
        return len(self._words)

    def sublist(self,size=3):
        """Return a random segment of _size_ length. The default is 3 words.
        """
        segment = []
        for i in range(size):
            segment.append(self.next())
        #printable = " ".join(segment)        
        return segment

    def random_name(self):
        """Return a string-formatted list of 3 random words.
        """
        words = self.sublist()
        return "%s %s %s" % (words[0], words[1], words[2])

def main():
    """Just to see it work...
    """
    wl = RandomWords()
    print wl.wordcount()
    print wl.next()
    print wl.sublist()
    print 'Three Word Name = %s' % wl.random_name()
    #print wl.get()

if __name__ == "__main__":
    main()

2 个答案:

答案 0 :(得分:6)

这是我的五美分:

  • 应该调用构造函数__init__
  • 您可以使用random.sample取消某些代码,它会执行next()sublist()所做的事情,但会预先打包。
  • 覆盖__iter__(定义班级中的方法),您可以摆脱RandomIter。您可以在docs中阅读更多相关内容(注意Py3K,某些内容可能与较低版本无关)。您可以使用yield,因为您可能知道或不知道创建一个生成器,因此浪费很少甚至没有内存。
  • random_name可以使用str.join代替。请注意,如果不保证它们是字符串,则可能需要转换这些值。这可以通过[str(x) for x in iterable]或内置map完成。

答案 1 :(得分:5)

第一个下意识的反应:我会将你的硬编码URL卸载到传递给类的构造函数参数中,也许可以从某个地方的配置读取;这将允许更容易的更改,而无需重新部署。

缺点是该类的消费者必须知道这些URL的存储位置...所以你可以创建一个伴侣类,其唯一的工作就是知道URL是什么(即在配置中,甚至是编码)以及如何获得它们。您可以允许您的类的使用者提供URL,或者如果未提供这些URL,则该类可以启动URL的伴随类。