独立代码在Anki插件中不起作用

时间:2017-06-03 19:25:03

标签: python beautifulsoup anki

以下代码工作正常,但当我使用与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应该在点击&#34;再次&#34;按钮。但是,它会引发一个属性错误:

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虚拟机上运行,​​除了Anki,以确保我使用的是Anki安装附带的python环境。

提前致谢!

1 个答案:

答案 0 :(得分:0)

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

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

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