python如何将转义的非unicode字符替换为它们各自的';雷亚尔';utf-8

python如何将转义的非unicode字符替换为它们各自的';雷亚尔';utf-8,python,unicode,encoding,utf-8,dbus,Python,Unicode,Encoding,Utf 8,Dbus,我对编程比较陌生,在为spotify for ubuntu(linux)编写一个与Snip相当的python时遇到了一个小问题 不知何故,我可以正确地编码标题,但我无法以同样的方式编码艺术家 当我尝试以同样的方式对艺术家进行编码时,我得到了以下结果: File "./songfinder.py", line 11, in currentplaying artiststr = str((metadata['xesam:artist']).encode('utf-8')) Attribute

我对编程比较陌生,在为spotify for ubuntu(linux)编写一个与Snip相当的python时遇到了一个小问题 不知何故,我可以正确地编码标题,但我无法以同样的方式编码艺术家

当我尝试以同样的方式对艺术家进行编码时,我得到了以下结果:

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
相关qna:


为什么它不能解决我的问题:我想打印/保存实际字符,而不是用类似的字符替换它

您得到的错误不是关于unicode,而是关于错误的类型。Python抱怨您试图从数组对象调用string方法
encode
。没有这个方法

我要尝试的第一个方法是删除这里多余的括号,它得到的artiststr如下:
artiststr=str(metadata['xesam:artist'])


但我不确定这是否有效。如果它不起作用,您需要找出元数据的类型['xesam:artist']。看起来不是字符串,而是数组。因此,您需要修复用数据填充
元数据['xesam:artist']
的代码。您可以尝试使用调试器或只使用
print()
函数查找
元数据['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)

查看您的问题
元数据
至少包含类似Unicode字符串的内容。艺术家的领域似乎是某种不可分割的,从艺术家开始。类似这样的内容(可以随意发布实际的元数据内容):

title
赋值行中,
str
是不必要的,因为编码Unicode字符串会返回
str
,但也不需要对其进行编码。Unicode字符串表示文本,因此请保持这种方式:

title =  metadata['xesam:title']
类似于
artist
赋值,但获取iterable的第一个元素:

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

python版本:2.7.11感谢您的帮助,有了您的信息,我可以进行简单的重新编码以使其正常工作。非常感谢你。最终的解决方案是:artiststr=str((元数据['xesam:artist'])[0]。编码('utf-8'))没有问题。:)是的,它可以工作,但是您应该确保数据集中不会有超过一个项目。
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