[英]How can I get the file names in directory with Chinese correctly in python?
如何在Python中用中文適當地獲取當前工作目錄中的名稱列表?
例如,在我的演示文件夾中,我有四個文件:“ folder_Chinese”“ folder_a”“ folder_b”“ folder_c”
RI中的命令可以使用以下命令來實現:
Sys.setlocale(category = "LC_ALL", locale = "zh_cn.utf-8")
setwd("~/desktop/example")
filenames=list.files()
filenames
"folder_中文" "folder_a" "folder_b" "folder_c"
但是我無法使用Anaconda在Python中實現這一點,盡管如果不將其分配給文件名,輸出看起來也很好(請參見下文); 中文文件名不正確。
# -*- coding: utf-8 -*-
import os
os.chdir('/Users/../Desktop/example')
! ls
filenames = ! ls
filenames
folder_a folder_b folder_c folder_中文
['folder_a', 'folder_b', 'folder_c', 'folder_\xe4\xb8\xad\xe6\x96\x87']
但是如果我繼續輸入
print(filenames)
print(filenames[3])
如果我提取此特定元素並直接打印,則可以觀察到中文。
['folder_a', 'folder_b', 'folder_c', 'folder_\xe4\xb8\xad\xe6\x96\x87']
folder_中文
我要強調的最后一件事是,如果我直接輸入中文,則只有明確使用打印件才能正確看到中文。 因此,無論有無印刷品,它都有很大的不同。
print('中文')
'中文'
中文
Out[65]: '\xe4\xb8\xad\xe6\x96\x87'
我的操作系統是Mac El Capitan(10.11.5),Anaconda的版本是:
2.7.13 |Anaconda custom (x86_64)| (default, Dec 20 2016, 23:05:08)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]
我回想起一個有關Python2漢字的問題。 Python3沒有問題。 我相信您需要在〜.bash_profile中添加以下內容:
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
然后:
source ~/.bash_profile
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.