Python;如何用各自的 'real' utf-8 替换转义的 non-unicode 字符

Python; How to replace escaped non-unicode characters with their respective 'real' utf-8

我是编程新手,我在为 ubuntu(linux) 编写一个 python 等同于 spotify 的 Snip 时遇到了一个小问题 我可以通过某种方式正确编码标题,但无法以相同的方式对艺术家进行编码

当我尝试以相同的方式对艺术家进行编码时,我得到了这个:

File "./songfinder.py", line 11, in currentplaying
    artiststr = str((metadata['xesam:artist']).encode('utf-8'))
AttributeError: 'dbus.Array' object has no attribute 'encode'

但是标题完全一样,而且有效。

代码目前有效,但有例如 \xd8 而不是 Ø,以及类似的:

import dbus
session_bus = dbus.SessionBus()
spotify_bus = session_bus.get_object("org.mpris.MediaPlayer2.spotify", "/org/mpris/MediaPlayer2")
spotify_properties = dbus.Interface(spotify_bus, "org.freedesktop.DBus.Properties")

def currentplaying():
    metadata = spotify_properties.Get("org.mpris.MediaPlayer2.Player", "Metadata")
    title =  str((metadata['xesam:title']).encode('utf-8'))
    artiststr = str((metadata['xesam:artist']))
    if ("dbus.string" in artiststr.lower()):
        artists = artiststr.split("(u")
        artist = artists[1]
        artists = artist.split(")],")
        artist = artists[0]
        artist = artist.replace("(u", "")
    else:
        artist = "'unknown'"

    artist = (artist.replace("'",""))

    playing = (artist + " - " + title + "             ")
    return playing

#save playing to file.txt

相关问题: Replace non-ascii chars from a unicode string in Python

为什么它不能解决我的问题:我想print/save真实的角色,而不是用类似的替换它

您遇到的错误与 unicode 无关,而是类型错误。 Python 抱怨您试图从数组对象调用字符串方法 encode。哪个没有这个方法。

我首先要尝试的是删除多余的括号,它会像这样获取 artiststr:artiststr = str(metadata['xesam:artist']).

但我不确定这是否可行。如果不行,你需要找出什么类型有元数据['xesam:artist']。看起来不是字符串,而是数组。因此,您需要修复用数据填充 metadata['xesam:artist'] 的代码。您可以尝试使用调试器或仅使用 print() 函数来找出 metadata['xesam:artist'] 的内容。或者也提供你问题中的相关代码。

最终程序,喜欢的可以随意使用:

import time
import dbus
session_bus = dbus.SessionBus()
spotify_bus = session_bus.get_object("org.mpris.MediaPlayer2.spotify", "/org/mpris/MediaPlayer2")
spotify_properties = dbus.Interface(spotify_bus, "org.freedesktop.DBus.Properties")


def currentplaying():
    metadata = spotify_properties.Get("org.mpris.MediaPlayer2.Player", "Metadata")
    title =  str((metadata['xesam:title']).encode('utf-8'))
    artiststr = str((metadata['xesam:artist'])[0].encode('utf-8'))

    artist = artiststr



    playing = (artist + " - " + title + "             ")
    return playing

while True:

    filetxt = open("/home/USER/Desktop/currentsongspotify.txt", "r")
    oldtitle = filetxt.read()
    filetxt.close()

    newtitle = str(currentplaying())


    if(newtitle == oldtitle):
        time.sleep(1)
    else:
        filetxt = open("/home/USER/Desktop/currentsongspotify.txt", "w")    #save newtitle to file, overwriting existing data
        filetxt.write(str(newtitle))
        print("new file saved:  " + newtitle)

查看您的问题 metadata 至少包含与 Unicode 字符串类似的内容。艺术家领域似乎是某种可迭代的,从艺术家开始。像这样(随意 post 实际元数据内容):

metadata = {'xesam:title':u'title','xesam:artist':[u'artist']}

title 赋值行中,str 是不必要的,因为无论如何都将 Unicode 字符串 returns 编码为 str,但也不需要对其进行编码。 Unicode 字符串表示文本,所以就这样吧:

title =  metadata['xesam:title']

类似于artist赋值,但获取可迭代对象的第一个元素:

artist = metadata['xesam:artist'][0]

接下来,在您的歌曲更新逻辑中,使用 io.open 打开 UTF-8 编码的文件。这允许直接写入 Unicode 字符串(文本),文件将处理编码。还可以使用 with 语句在 with 结束时自动关闭文件。

具有建议更改的程序:

import time
import dbus
import io
session_bus = dbus.SessionBus()
spotify_bus = session_bus.get_object("org.mpris.MediaPlayer2.spotify", "/org/mpris/MediaPlayer2")
spotify_properties = dbus.Interface(spotify_bus, "org.freedesktop.DBus.Properties")

def currentplaying():
    metadata = spotify_properties.Get("org.mpris.MediaPlayer2.Player", "Metadata")
    title =  metadata['xesam:title']
    artist = metadata['xesam:artist'][0]
    playing = artist + " - " + title + "             "
    return playing

while True:
    with io.open('currentsongspotify.txt', encoding='utf8') as filetxt:
        oldtitle = filetxt.read()
    newtitle = currentplaying()
    if newtitle == oldtitle:
        time.sleep(1)
    else:
        with io.open('currentsongspotify.txt','w',encoding='utf8') as filetxt: # save newtitle to file, overwriting existing data
            filetxt.write(newtitle)
        print 'new file saved:',newtitle