Python:看起来像是空格但不是空格的字符。它是什么? [英] Python: A character that appears to be a space but isn't a space. What is it?

查看:331
本文介绍了Python:看起来像是空格但不是空格的字符。它是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Python 3.4中的版本。

This is in Python 3.4.

我正在为自己编写第一个程序,但有一定的局限性。我正在尝试根据python中的元数据重命名所有音频文件。但是,当我尝试重命名文件时,有时无法完成重命名。我认为这是由于无效字符引起的。问题是我不知道这是什么角色。对我来说,它看起来像是一个空间,但不是。

I'm writing my first program for myself and I'm stuck at a certain part. I'm trying to rename all of my audio files according to its metadata in python. However, when I try to rename the files, it doesn't finish renaming it sometimes. I think it is due to an invalid character. The problem is that I don't know what character it is. To me, it looks like a space but it isn't.

我的代码在这里:

from tinytag import TinyTag
import os

print("Type in the file directory of the songs you would like to rename and organize:")
directory = input()
os.chdir(directory)
file_list = os.listdir(directory)

for item in file_list:
    tag = TinyTag.get(item)
    title = str(tag.title)
    artist = str(tag.artist)
    if artist[-1] == "\t" or artist[-1] == " ":
        print("Found it!")
    new_title = artist + "-" + title + ".mp3"
    #os.rename(item, new_title)
    print(new_title)

这是它输出的列表:
http://imgur.com/tfgBdMZ

应该输出 Artist-Title.mp3,但有时会输出 Artist-Title.mp3 -标题.mp3。当空间到位时,python会在此时停止重命名。这样做的第一个条目是Arethra Franklin。它只是将文件命名为Arethra Franklin而不是Arethra Franklin-Dr.Feelgood.mp3

It is supposed to output "Artist-Title.mp3" but sometimes it outputs "Artist -Title .mp3". When the space is there, python stops renaming it at that point. The first entry that does so is Arethra Franklin. It simply names the file Arethra Franklin rather than Arethra Franklin-Dr.Feelgood.mp3

为什么这样做?我的主要问题是那个空间是什么?我尝试设置==布尔值来查看它是否为空格(),但不是。

Why does it do this? My main question is what is that space? I tried setting up a == boolean to see if it is a space (" ") but it isn't.

一旦碰到空格,它将停止重命名操作。但是,当它碰到正常空间时却没有。

It ends the renaming by stopping once it hits that "space". It doesn't when it hits a normal space however.

推荐答案

文件名中可能包含一些unicode。如果您要查找的只是文件重命名器,则可以使用 str.encode 并通过将错误替换为字符来处理错误。例如:

It's possible that the filename has some unicode in it. If all you are looking for is a file renamer, you could use str.encode and handle the errors by replacing them with a ? character. As an example:

# -*- coding: utf-8 -*-
funky_name = u"best_song_ever_пустынных.mp3"
print (funky_name)
print (funky_name.encode('ascii','replace'))

这给出:

best_song_ever_пустынных.mp3
best_song_ever_?????????.mp3

如评论中所述,您可以使用 ord 来找出违规空间确实是。

As mentioned in the comments, you can use ord to find out what the "offending space" really is.

这篇关于Python:看起来像是空格但不是空格的字符。它是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆