簡體   English   中英

蟒蛇; 如何使用各自的“真實”utf-8替換轉義的非unicode字符

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

我是一個比較新的編程,我有一個小問題,寫一個python相當於Snip for spotify for ubuntu(linux)不知怎的,我可以正確編碼標題,但我無法以同樣的方式編碼藝術家

當我嘗試以相同的方式對藝術家進行編碼時,我得到了這個:

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: 用Python中的unicode字符串替換非ascii字符

為什么它不能解決我的問題:我想打印/保存實際的字符,而不是用類似的字符替換它

你得到的錯誤不是關於unicode,而是關於錯誤的類型。 Python抱怨你試圖從數組對象調用字符串方法encode 哪個沒有這個方法。

我要嘗試的第一個是刪除多余的括號,這樣得到的藝術家就像這樣: artiststr = str(metadata['xesam:artist'])

但我不確定這會起作用。 如果它不起作用,您需要找出元數據的類型['xesam:artist']。 看起來它不是字符串,而是數組。 因此,您需要修復使用metadata['xesam:artist']填充metadata['xesam:artist']的代碼。 您可以嘗試使用調試器或僅使用print()函數來查找metadata['xesam:artist']的內容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字符串的內容。 藝術家領域似乎是與藝術家一起開始的某種可迭代的。 像這樣的東西(隨意發布實際的元數據內容):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM