由于外来字符而导致定位文件

时间:2015-11-10 19:19:00

标签: python xml unicode itunes python-3.5

这是我第一次写这里,所以我希望我能做好一切。 我在Win10上使用python 3.5,我试图"同步"音乐从Itunes到我的Android设备。基本上,我正在阅读Itunes Library XML文件并获取所有文件的位置(所以我可以将它们复制/粘贴到我的手机中),但是我对包含外来字符的歌曲有问题。

import getpass
import re
import os
from urllib.parse import unquote

user = getpass.getuser()
ITUNES_LIB_PATH = "C:\\Users\\%s\\Music\\Itunes\\iTunes Music Library.xml" % user
ITUNES_SONGS_FILE = "ya.txt"


def write(file, what, newline=True):
    with open(file, 'a', encoding="utf8") as f:
        if  not os.path.isfile(what):
            print("Issue locating file %s\n" % what)
        if newline:
            what+"\n"
        f.write(what)


def get_songs(file=ITUNES_LIB_PATH):
    with open(file, 'r', encoding="utf8") as f:
        f = f.read()
        songs_location = re.findall("<key>Location</key><string>file://localhost/(.*?)</string>", f)
        for song in songs_location:
            song = unquote(song.replace("/", '\\'))
            write(ITUNES_SONGS_FILE, song)


get_songs()

输出:

Issue locating file C:\Users\Dymy\Desktop\Media\Norin &#38;amp; Rad - Bird Is The Word.mp3

我该如何处理&#34;&amp; amp;&#34;在文件名?

1 个答案:

答案 0 :(得分:0)

您的代码中存在一些相关问题,例如,未转义的xml字符引用,使用regular expressions to parse xml导致的硬编码字符编码。要解决这些问题,请使用xmlSELECT count(*) FROM `Members_Information` WHERE `Username`='".$username."'"); $row = $Usernameresults->fetch_row()) { if($row[0] > 0 ){ echo "Username has already been choosen"; } echo $row['Username']; } 解析器或使用更具体的xml.etree.ElementTree