首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python脚本使用genanki创建anki闪存卡(预期str实例,dict找到错误)

Python脚本使用genanki创建anki闪存卡(预期str实例,dict找到错误)
EN

Stack Overflow用户
提问于 2018-06-27 16:54:10
回答 1查看 3.6K关注 0票数 0

该程序使用熊猫在一个名为" list“的excel文件的第一列中获取一个英文单词列表,该列的标题是" words”,单词位于"Sheet1“中。

然后将单词存储为字符串列表。

PyDictionaryGoogletrans反式是通过创建词典和翻译器来使用的,其中译者被翻译成译文,以便将列表中的单词翻译成目的语言“丹麦语”。

然后创建一个简单的for循环,在该循环中,翻译单词列表中的每一个翻译都与其来源、->、目的地和定义一起打印。

在下面的守则中说明了这一点:

代码语言:javascript
运行
复制
from googletrans import Translator
import pandas as pd
from PyDictionary import PyDictionary

# Load excel file and parse the list of words as strings
file_location = "/Users/.../List.xlsx"
xl_workbook = pd.ExcelFile(file_location)
df = xl_workbook.parse("Sheet1")
aList = df['words'].tolist()
[str(i) for i in aList]

# Use PyDictionary to load definitions of words
dictionary = PyDictionary()

# Translate the list of strings into target language and give definitions
translator = Translator()
translations = translator.translate(aList, dest='da')

# Simple for-loop printing the words
for translation in translations:
    print(
        translation.origin, ' -> ', translation.text,
        dictionary.meaning(translation.origin)
    )

这个程序实际上运行并产生了我希望的结果。但是,问题发生在下一步,如下所述:

我想把这些单词输入我最喜欢的闪存卡程序安基中.Anki是用Python编写的,有一个名为吉南基的非官方发行版。然而,这是我遇到问题的时候。

现在,我在上面的代码中添加以下4项内容:

  1. 我按照genanki的建议定义了my_model,并创建了一个简单的闪存卡模型。这包括一个随机硬编码数字( Anki需要)、模型名称、一些字段和卡片类型的模板。
  2. 我将my_deck定义为具有硬编码随机数和名称的特定的闪存卡。
  3. 我将for循环更改为现在直接将翻译和定义运行到一个名为aNote的变量中,该变量由genanki.note操作符组成,每次将注释添加到my_deck时迭代翻译。
  4. 我可以和Anki一起打开我的Anki文件。

这可以在下面的代码中看到:

代码语言:javascript
运行
复制
from googletrans import Translator
import pandas as pd
from PyDictionary import PyDictionary
import genanki

# Load excel file and parse the list of words as strings
file_location = "/Users/.../List.xlsx"
xl_workbook = pd.ExcelFile(file_location)
df = xl_workbook.parse("Sheet1")
aList = df['words'].tolist()
[str(i) for i in aList]

# Use PyDictionary to load definitions of words
dictionary = PyDictionary()

# Use genanki to define a flashcard model
my_model = genanki.Model(
    2042686211,
    'Simple Model',
    fields=[
        {'name': 'Question'},
        {'name': 'Answer'},
    ],
    templates=[
        {
            'name': 'Card 1',
            'qfmt': '{{Question}}',
            'afmt': '{{FrontSide}}<hr id="answer">{{Answer}}',
        },
    ])

# Specify the deck with genanki
my_deck = genanki.Deck(
    1724897887,
    'TestV3v1')

# Translate the list of strings with definition and add as note to anki
translator = Translator()

translations = translator.translate(aList, dest='da')
for translation in translations:
    aNote = genanki.Note(
        model=my_model, fields=[translation.origin, translation.text]
    )
    my_deck.add_note(aNote)

# Output anki file in desired folder
genanki.Package(my_deck).write_to_file(
    '/Users/.../TestV3v1.apkg')

这段代码也执行得很好,并生成一个可以在Anki中打开的文件,然后卡片在闪存卡前面显示原始单词,背面显示翻译。

我的问题

为了完成我的项目,我想在每一张卡片的背面加上一个定义。我最初以为我只需要更正my_model =genanki.model(.)变量,方法是添加另一个字段,以便只需将dictionary.meaning(translation.origin)添加到for-循环中的便笺生成器中。

但是,当试图添加定义以确保它们顺利运行时,我遇到了一些问题。考虑下面的守则:

代码语言:javascript
运行
复制
for translation in translations:
    aNote = genanki.Note(
        model=my_model, fields=[translation.origin,
                                dictionary.meaning(translation.origin)
                                ]
    )
    my_deck.add_note(aNote)

我预期卡片会像往常一样打印,正面是原始单词,背面是定义,但是使用这个for-循环运行完整的代码会给出以下错误:

代码语言:javascript
运行
复制
Error: The Following Error occured: list index out of range
Error: The Following Error occured: list index out of range
Error: The Following Error occured: list index out of range
Error: A Term must be only a single word
Error: A Term must be only a single word
Error: A Term must be only a single word
Error: A Term must be only a single word
Error: A Term must be only a single word
Error: The Following Error occured: list index out of range
Error: A Term must be only a single word
Error: A Term must be only a single word
Error: The Following Error occured: list index out of range
Error: The Following Error occured: list index out of range
Error: The Following Error occured: list index out of range
Error: A Term must be only a single word
Error: A Term must be only a single word
Error: A Term must be only a single word
Error: A Term must be only a single word
Error: A Term must be only a single word
Error: A Term must be only a single word
Error: The Following Error occured: list index out of range
Error: A Term must be only a single word
Error: The Following Error occured: list index out of range
Traceback (most recent call last):
  File "/Users/Lehmann/Desktop/XYZ/Programming/Translator/TranslatorProgramv3.py", line 51, in <module>
    '/Users/Lehmann/Desktop/XYZ/Programming/Translator/TestV3v1.apkg')
  File "/anaconda3/lib/python3.6/site-packages/genanki/__init__.py", line 313, in write_to_file
    self.write_to_db(cursor, now_ts)
  File "/anaconda3/lib/python3.6/site-packages/genanki/__init__.py", line 331, in write_to_db
    deck.write_to_db(cursor, now_ts)
  File "/anaconda3/lib/python3.6/site-packages/genanki/__init__.py", line 267, in write_to_db
    note.write_to_db(cursor, now_ts, self.deck_id)
  File "/anaconda3/lib/python3.6/site-packages/genanki/__init__.py", line 228, in write_to_db
    self._format_fields(),        # flds
  File "/anaconda3/lib/python3.6/site-packages/genanki/__init__.py", line 240, in _format_fields
    return '\x1f'.join(self.fields)
TypeError: sequence item 1: expected str instance, dict found

我怀疑这部分“预期的str实例,迪克发现”给我带来麻烦,然而,这是我的第一个python项目,我不是一个程序员,所以我希望有人能帮助我理解这个问题。

BR

米克尔

EN

回答 1

Stack Overflow用户

发布于 2018-07-19 05:31:36

始终确保在使用变量时检查变量的类型。根据我的发现,使用dictionary.meaning(.)将类型更改为字典。所以你要做的就是:

代码语言:javascript
运行
复制
meaning=dictionary.meaning(translation.origin)
meaning_to_string=''.join('{}: {}'.format(key,val) for key,val in meaning.items())

#moving to aNote
aNote=genanki.Note(model=my_model, fields=[translation.origin,meaning_to_string])
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51067932

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档