0

我刚刚发现,由于某种原因,在使用 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()如果有一些像'.


编辑:替代解决方案

除了我接受的解决方案之外,另一种解决方案是将pyperclip从最新版本(现在它1.6.4)降级到较低版本(1.6.1对我有用)。

4

2 回答 2

1

此问题已在 1.6.5 中修复,因此您只需运行pip install -U pyperclip.

于 2018-09-24T07:59:58.747 回答
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()是一种黑客行为,出于多种原因不鼓励使用。

于 2018-09-06T00:18:54.447 回答