2

下面的代码工作正常,但是当我使用与 Anki 插件相同的代码时,BeautifulSoup会引发属性错误。

这是工作代码:

from bs4 import BeautifulSoup

s = '''<style>.card {
 font-family: arial;
 font-size: 20px;
 text-align: center;
 color: black;
 background-color: white;
 }
 </style>question

 <hr id=answer>

 answer''' 

soup = BeautifulSoup(s, "html.parser")
soup.find("style").clear()
words = soup.text.strip().split()
print words

>>> [u'question', u'answer']

这是 Anki 插件文件的内容:

from aqt.reviewer import Reviewer
from aqt.editor import *

def newAnswerCard(self, ease):
    "Reschedule card and show next."
    if self.mw.state != "review":
        # showing resetRequired screen; ignore key
        return
    if self.state != "answer":
        return
    if self.mw.col.sched.answerButtons(self.card) < ease:
        return
    if ease == 1:
        s = '''<style>.card {
         font-family: arial;
         font-size: 20px;
         text-align: center;
         color: black;
         background-color: white;
        }
        </style>question

        <hr id=answer>

        answer''' 

        soup = BeautifulSoup(s, "html.parser")
        soup.find("style").clear()
        words = soup.text.strip().split()

    self.mw.col.sched.answerCard(self.card, ease)
    self._answeredIds.append(self.card.id)
    self.mw.autosave()
    self.nextCard()

origAnswerCard = Reviewer._answerCard
Reviewer._answerCard = newAnswerCard

Anki 应该在单击“再次”按钮时运行此代码。但是,它会引发一个属性错误:

Traceback (most recent call last):
  File "aqt\webview.py", line 21, in link
  File "aqt\reviewer.py", line 323, in _linkHandler
  File "C:\Users\A\AppData\Roaming\Anki2\addons\amintest2.py", line 27, in newAnswerCard
    soup = BeautifulSoup(s, "html.parser")
  File "thirdparty\BeautifulSoup.py", line 1521, in __init__
  File "thirdparty\BeautifulSoup.py", line 1146, in __init__
  File "thirdparty\BeautifulSoup.py", line 1188, in _feed
  File "sgmllib.py", line 104, in feed
  File "sgmllib.py", line 138, in goahead
  File "sgmllib.py", line 296, in parse_starttag
  File "sgmllib.py", line 338, in finish_starttag
  File "thirdparty\BeautifulSoup.py", line 1343, in unknown_starttag
AttributeError: 'str' object has no attribute 'text'

我想我在bs4导入from aqt.editor import *. 以下是 的内容act.editor

https://github.com/dae/anki/blob/4693e71104dbe7d19a3e7242b0c2e67a1b4107d8/aqt/editor.py

我这样做只是因为我无法在插件中导入from bs4 import BeautifulSoup(我的另一个困惑!)。

我在一个没有安装 python 的 win7 virtualbox 上运行,除了 Anki,以确保我使用的是 Anki 安装附带的 python 环境。

提前致谢!

4

1 回答 1

0

您需要一份 Beautiful Soup 4。在此处下载最新版本:

http://www.crummy.com/software/BeautifulSoup/bs4/download/

解压缩代码并将文件夹“bs4”复制到 Anki Add-On 文件夹。然后重启 Anki。

于 2018-07-07T00:23:28.357 回答