我的第一个Python程序!有人愿意回顾一下,帮助我提高吗?
我刚刚编写了我的第一个Python程序,它运行正常!这是一个将字幕文件重命名为其匹配视频文件的程序,以便媒体播放器拾取字幕(例如,如果目录中存在名为“the.Office.S03E01.avi”的文件,则将“the_Office_3x01.str”重命名为“the.Office.S03E01.str”) 我希望有人评论/批评我的代码,并帮助我改进我的编码风格,使之更加Python-y。您可以在以下位置找到代码: 正如我所说,这是我使用Python编写的第一个程序,因此请随意评论以下内容:我的第一个Python程序!有人愿意回顾一下,帮助我提高吗?,python,Python,我刚刚编写了我的第一个Python程序,它运行正常!这是一个将字幕文件重命名为其匹配视频文件的程序,以便媒体播放器拾取字幕(例如,如果目录中存在名为“the.Office.S03E01.avi”的文件,则将“the_Office_3x01.str”重命名为“the.Office.S03E01.str”) 我希望有人评论/批评我的代码,并帮助我改进我的编码风格,使之更加Python-y。您可以在以下位置找到代码: 正如我所说,这是我使用Python编写的第一个程序,因此请随意评论以下内容: 样式
- 样式(缩进、变量名、约定等)
- 设计
- 我应该使用的Python特性我没有
- 我对图书馆的使用
match = [regex.match(str) for regex in episodeRegExes if regex.match(str)]
然后
def getEpisodeTuple(iterable):
episodeTuple = [episodeChunk(chunk)
for chunk in iterable
if episodeChunk(chunk)]
if episodeTuple:
assert len(episodeTuple) == 1
return episodeTuple[0]
else:
return None
请注意,这里的列表理解会计算两次episodeChunk(chunk),其中每一个都会执行两次正则表达式匹配,因此在成功的情况下,您将匹配四次正则表达式
在最后一段代码中,(a)将列表称为元组,(b)构建一个列表,然后断言它只有一个元素,然后返回该元素。这样会更简单:
def getEpisodeTuple(iterable):
for chunk in iterable:
echunk = episodeChunk(chunk)
if echunk:
return echunk
6) 了解有关标准库的更多信息。例如,此代码:
def splitWithAny(string, delimiters):
"Splits the string with any of the strings of delimiters"
return reduce(
lambda iterable, delim: reduce(
lambda lst,chunk: lst + chunk.split(delim),
iterable,
[]),
delimiters,
[string])
def splitName(fileName):
"Splits the fileName into smaller and hopefully significant chunks"
delimiters = [" ", ".", "_", "-"]
return filter(None, splitWithAny(fileName, delimiters))
我认为(我不确定,因为reduce(lambda)(reduce(lambda)))可以简化为:
def splitName(fileName):
return re.split("[ ._-]+", fileName)
应位于第一行#/usr/bin/env python
- 使用[docstrings][1]进行多行注释和函数描述
- 在代码中包含一般描述,这样我们就不必猜测它的用途李>
- 避免使用单行函数,结构更具描述性
splitNames = [splitName(string) for string in stringiterable]
chunkChunks = lambda chunks: [chunk for chunk in chunks if not episodeChunk(chunk)]
return [(getEpisodeTuple(chunks),chunkChunks(chunks) for chunks in splitNames]
这样会更好。然而,现在对于普通用户来说,没有迁移的选项。这确实属于代码审查,但是+1。@dheerosaur:
post.replace('python-y','Pythonic')
会更Pythonic。我喜欢你的标题。当我看到一个格式很好的标题时,我的分数总是更高。我不知道代码审查网站。谢谢你指出!我认为函数式加起来,口味各异。我认为有一些特定的原因(在这里的编辑中添加)表明这种风格在这种情况下没有帮助。我可能从使用Python的人群中的一个偏斜的部分收集到,在Python社区中,功能性很强的编程风格,甚至比这里使用的编程风格要低,通常是不受欢迎的。我认为部分原因是它通常避免给例程命名,这使得代码不那么明确和可读。
splitNames = [splitName(string) for string in stringiterable]
chunkChunks = lambda chunks: [chunk for chunk in chunks if not episodeChunk(chunk)]
return [(getEpisodeTuple(chunks),chunkChunks(chunks) for chunks in splitNames]