有没有更好/更具pythonified的方法来做到这一点?
在我的新工作中,我一直在自学Python,并且非常喜欢这种语言。我写了一个简短的类来做一些基本的数据操作,我对此很有信心 但是,我的结构化/模块化编程时代的旧习惯很难打破,我知道一定有更好的方法来写这篇文章。所以,我想知道是否有人愿意看看下面的内容,并提出一些可能的改进,或者让我找到一个可以帮助我自己发现这些内容的资源 一个简短的提示:RandomItems根类是由其他人编写的,我仍然在思考itertools库。此外,这不是整个模块——只是我正在处理的类,它是先决条件 你觉得怎么样有没有更好/更具pythonified的方法来做到这一点?,python,optimization,string,random,Python,Optimization,String,Random,在我的新工作中,我一直在自学Python,并且非常喜欢这种语言。我写了一个简短的类来做一些基本的数据操作,我对此很有信心 但是,我的结构化/模块化编程时代的旧习惯很难打破,我知道一定有更好的方法来写这篇文章。所以,我想知道是否有人愿意看看下面的内容,并提出一些可能的改进,或者让我找到一个可以帮助我自己发现这些内容的资源 一个简短的提示:RandomItems根类是由其他人编写的,我仍然在思考itertools库。此外,这不是整个模块——只是我正在处理的类,它是先决条件 你觉得怎么样 import
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()
这是我的五分钱:
- 构造函数应该被称为
\uuuuu init\uuuu
- 您可以使用
取消一些代码,它执行random.sample
和next()
子列表()所做的操作,但它是预打包的
- 重写
(在类中定义方法),您可以摆脱\uuuu iter\uuuuu
。您可以在中阅读更多关于它的内容(注意Py3K,一些内容可能与较低版本无关)。您可以使用随机iter
,因为您可能知道也可能不知道,它创建了一个生成器,因此几乎不浪费内存yield
可以使用。请注意,如果不能保证值是字符串,则可能需要转换这些值。这可以通过random\u name
或内置[str(x)for x in iterable]
完成map
- 第一个下意识的反应:我会将您的硬编码URL卸载到传递给类的构造函数参数中,并可能从某个配置读取;这将允许更容易的更改,而无需重新部署
这样做的缺点是类的使用者必须知道这些URL存储在哪里。。。因此,您可以创建一个伴生类,它唯一的任务就是知道URL是什么(即在配置中,甚至是硬编码中)以及如何获取它们。您可以允许类的使用者提供URL,或者,如果没有提供URL,则类可以在同伴类中查找URL 对不起,不管语言如何,我倾向于使用SOLID。我想不出任何特定于Python的东西能让你的类更具Python风格。将硬编码的URL移到一个单独的类中是我在旧java课程中应该记住的事情。谢谢你指出这一点@格雷格·瓜希尔:没问题非常好的建议,非常感谢您抽出时间。收益率是我从未想过的事情,我不好意思承认我忽略了random.sample。