Преобразуйте имена файлов Python в unicode

-(UIButton *)addButton:(NSString *)title :(CGRect)frame : (SEL)selector :(UIImage *)image :(int)tag{

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = frame;
[btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
[btn setTitle:title forState:UIControlStateNormal];
[btn setImage:image forState:UIControlStateNormal];
btn.backgroundColor = [UIColor clearColor];
btn.tag = tag;

return btn;

}

и вы можете добавить его в представление:

[self.view addSubview:[self addButton:nil :self.view.frame :@selector(btnAction:) :[UIImage imageNamed:@"img.png"] :1]];
17
задан Bernd 1 October 2011 в 12:11
поделиться

4 ответа

Если вы передадите строку Unicode в os.walk () , вы получите результаты Unicode :

>>> list(os.walk(r'C:\example'))          # Passing an ASCII string
[('C:\\example', [], ['file.txt'])]
>>> 
>>> list(os.walk(ur'C:\example'))        # Passing a Unicode string
[(u'C:\\example', [], [u'file.txt'])]
45
ответ дан 30 November 2019 в 10:21
поделиться

os.walk не указано, чтобы всегда использовать os.listdir , но и не указано, как обрабатывается Unicode. Однако os.listdir действительно говорит:

Изменено в версии 2.3: В Windows NT / 2k / XP и Unix, если путь указан Объект Unicode, результатом будет список объектов Unicode. Не декодируемый имена файлов по-прежнему будут возвращены как строковые объекты.

Подходит ли вам простое использование аргумента Unicode?

for dirpath, dirnames, filenames in os.walk(u"."):
  print dirpath
  for fn in filenames:
    print "   ", fn
1
ответ дан 30 November 2019 в 10:21
поделиться

No, they are not encoded in Pythons internal string representation, there is no such thing. They are encoded in the encoding of the operating system/file system. Passing in unicode works for os.walk though.

I don't know how os.walk behaves when filenames can't be decoded, but I assume that you'll get a string back, like with os.listdir(). In that case you'll again have problems later. Also, not all of Python 2.x standard library will accept unicode parameters properly, so you may need to encode them as strings anyway. So, the problem may in fact be somewhere else, but you'll notice if that is the case. ;-)

If you need more control of the decoding you can't always pass in a string, and then just decode it with filename = filename.decode() as usual.

1
ответ дан 30 November 2019 в 10:21
поделиться

более прямым способом может быть следующее - найти кодировку вашей файловой системы, а затем преобразовать ее в Unicode. например,

unicode_name = unicode(filename, "utf-8", errors="ignore")

, чтобы пойти другим путем,

unicode_name.encode("utf-8")
2
ответ дан 30 November 2019 в 10:21
поделиться
Другие вопросы по тегам:

Похожие вопросы: