gpt4 book ai didi

python - 用于组织音乐的 python 脚本中的缩进错误

转载 作者:太空宇宙 更新时间:2023-11-04 04:37:58 25 4
gpt4 key购买 nike

我过去制作过这个脚本,现在想使用它,但尝试运行它时出现错误。这个脚本是关于组织我的音乐的。我有一个按标签组织的目录,想要从标签和年份目录中的目录名称中获取艺术家姓名,并在艺术家和年份目录中创建新目录。

label内的目录名称是这样的

LabelName_[艺术家专辑名称]_2015-08-09

并且想要在艺术家目录和年份目录(按日期)内创建符号链接(symbolic link),如下所示

2015-08-09_[艺术家-AlbumName]_LabelName

import os
basedir = "/home/zab/Music/#01.Label"
artist_parent_dir = "/home/zab/Music/#03.Artist"
date_parent_dir = "/home/zab/Music/#04.ReleaseDate"
for fn in os.listdir(basedir):
label_path = os.path.join( basedir, fn)
for album in os.listdir(label_path):
i = 1
words = album.split("_")
for word in words:
if i == 1:
label = word
elif i == 2:
name = word
else:
date = word
i = i + 1
artist_album = name.split("-")
j = 1
for part in artist_album:
if j == 1:
artist = part.replace("[","")
j = j + 1
date_parts = date.split("-")
z = 1
for part_two in date_parts:
if z == 1:
year = part_two
z = z + 1
if not os.path.isdir(os.path.join(artist_parent_dir,artist)):
os.mkdir(os.path.join(artist_parent_dir,artist))
if not os.path.isdir(os.path.join(date_parent_dir,year)):
os.mkdir(os.path.join(date_parent_dir,year))
src = os.path.join(label_path,album)
artist_dst = os.path.join(artist_parent_dir, artist, name + "_" + label + "_" + date)
year_dst = os.path.join(date_parent_dir,year, date + "_" + name + "_" + label)
if not os.path.exists(artist_dst):
os.symlink(src, artist_dst)
if not os.path.exists(year_dst):
os.symlink(src, year_dst)

File "/home/zab/Music/_Scripts/OrganizeByArtist.py", line 22
artist = part.replace("[","")
^
IndentationError: expected an indented block

出了什么问题?是part.replace过时了还是什么?任何改进此脚本的建议将不胜感激。

最佳答案

您正在混合制表符和空格;从您的帖子中获取来源显示:

>>> '''\
... for part in artist_album:
... if j == 1:
... artist = part.replace("[","")
... '''.splitlines()
[' for part in artist_album:', '\t if j == 1:', ' artist = part.replace("[","")']
>>> from pprint import pprint
>>> pprint(_)
[' for part in artist_album:',
'\t if j == 1:',
' artist = part.replace("[","")']

请注意 if 行开头的 \t。 Python 将制表符扩展为 8 个空格,但您可能将编辑器设置为使用 4 个空格。所以 Python 看到了这个:

for part in artist_album:
if j == 1:
artist = part.replace("[","")']

您的编辑器向您展示的位置:

for part in artist_album:
if j == 1:
artist = part.replace("[","")']

将您的编辑器配置为仅使用空格进行缩进。如果这样配置的话,一个好的编辑器会为您将 TAB 键转换为空格。

引自Python Style Guide (PEP 8):

Spaces are the preferred indentation method.

Tabs should be used solely to remain consistent with code that is already indented with tabs.

关于python - 用于组织音乐的 python 脚本中的缩进错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31902770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com