gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:11:39 25 4
gpt4 key购买 nike

我对编程还比较陌生,我在为 ubuntu(linux) 的 spotify 编写一个相当于 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

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

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

最佳答案

看看你的问题 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

关于Python;如何用各自的 'real' utf-8 替换转义的非 unicode 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39434177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com