蟒蛇;如何使用各自的“真实”utf-8替换转义的非unicode字符

时间:2016-09-11 08:20:40

标签: python unicode encoding utf-8 dbus

我对编程比较陌生,我有一个小问题,为ubuntu(linux)写一个python等效的snip for spotify 不知何故,我可以正确编码标题,但无法以相同的方式编码艺术家

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

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: Replace non-ascii chars from a unicode string in Python

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

3 个答案:

答案 0 :(得分:0)

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

我要尝试的第一个是删除多余的括号,这样就得到像这样的艺术家:artiststr = str(metadata['xesam:artist'])

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

答案 1 :(得分:0)

最终节目,如果您愿意,请随时使用:

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)

答案 2 :(得分:0)

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

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

title分配行中,str是不必要的,因为编码Unicode字符串无论如何都会返回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