Python pyperclip无法复制解码后的

时间:2018-09-05 23:55:52

标签: python string utf-8 decode pyperclip

我刚刚发现,由于某些原因,使用pyperclip复制已解码的字符串(使用utf-8)时,它将引发错误。

import pyperclip
with open('chat.txt' 'r') as f:
    string = f.read()
# the string is encoded in utf-8 in order to be able to write down `'`, `emoji` and other special signs or symbol
pyperclip.copy(string.decode('utf-8'))

它将引发此错误:PyperclipException: only str, int, float, and bool values can be copied to the clipboard, not unicode

我找到了一种使用str()来解决该问题的方法,但是后来发现,由于str()在某些字符'下不起作用,因此1.6.4不起作用。 / p>


编辑:替代解决方案

除了我接受的解决方案之外,另一种解决方案是将 pyperclip 从最新版本(现在为1.6.1)降级为较低版本(// Connect to the SignalR hub. string url = $"http://{DataService.HostName}:{DataService.MainPort.ToString()}/hub"; try { MediaHubConnection = new HubConnectionBuilder().WithUrl(url).Build(); } catch (Exception e) { // Handle exception } )为我)。

2 个答案:

答案 0 :(得分:1)

此问题已在1.6.5中修复,因此您所要做的就是通过运行NLTK_DATA更新pyperclip。

答案 1 :(得分:0)

您似乎在使用非ASCII引号时遇到了一些问题。我建议您使用Python 3.7。这是一个示例:

import pyperclip

with open('chat.txt', 'r') as f:
    string = f.read()
pyperclip.copy(string)

这是Python 2.7的替代方法:

import pyperclip
import sys
reload(sys)
sys.setdefaultencoding('utf8')

with open('chat.txt', 'r') as f:
    string = f.read()

pyperclip.copy(string)

警告:正如@lenz在评论中所指出的那样,sys.setdefaultencoding()的使用是一种黑客手段,不鼓励使用number of reasons