【问题标题】:Issue locating files due to foreign characters由于外来字符而导致文件定位问题
【发布时间】:2016-02-11 19:03:37
【问题描述】:

这是我第一次在这里写作,所以我希望我一切都好。 我在 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

我应该如何处理那个“&”在文件名中?

【问题讨论】:

  • 也许你可以再次使用replace() 将所有&amp;amp;s 变成&amp;
  • 或使用 html 库,如答案on here
  • 感谢@RNar,它解决了这个问题!我想知道是否有办法避免 utf8 编码避免 read() 和 write()...
  • &amp;#38;amp; 是转义两次的 & 符号。这与任何字符编码无关。
  • 我必须通过将“utf8”设置为编码来克服 UnicodeError,这会改变字符串并导致文件路径错误,我想知道是否有任何方法可以在不编码为 utf8 的情况下使用这些路径。 @roeland

标签: python xml unicode itunes python-3.5


【解决方案1】:

您的代码中存在一些相关问题,例如,未转义的 xml 字符引用、使用 regular expressions to parse xml 导致的硬编码字符编码。要修复它们,请使用 xml 解析器,例如 xml.etree.ElementTree 或更具体的 pyitunes library (I haven't tried it)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多