0

我正在尝试用带有问题和答案的 html 标记的文本文件制作 CSV 文件。不幸的是,我已经尝试过,但无法在 LibreOffice 或任何其他 CSV 兼容软件中打开它。我想要做的是转换这样的东西:

<b>Question 1:</b> What is the capital of United States?
<b>Answer:</b> Washington, D.C.

<b>Question 2:</b> What is the capital of United States?
<b>Answer:</b> Washington, D.C.

<b>Question 3:</b> What is the capital of United States?
<b>Answer:</b> Washington, D.C.

等等。

结果应该是:

Question SEPARATOR Answer

*SEPARATOR 不能是颜色或分号,因为问题可能包含最重要的字符(冒号、分号、点)

我想导入 Anki,它支持 CSV 文件。

我尝试用# 之类的特殊符号分隔问题和答案,并且仅在 LibreOffice/OpenOffice 中解析问题,并且问题文本永远不能包含换行符。如果文本包含换行符,CSV 就会混乱。

4

1 回答 1

0

这是一个将卡片转换为 CSV 格式的小 Python 脚本:

import re
import csv

questions = [[]]

with open("original.file", "rt") as f:
    for line in f:
        line = line.strip()
        if line:
            questions[-1].append(line)
        else:
            questions.append([])

# Now we've got the questions in a 2D list.
# Let's just make sure it loaded properly.
assert all(len(question) == 2 for question in questions)

# Let's write a CSV file now.
with open("output.csv", "wt", newline="") as f:
    writer = csv.writer(f)
    for q, a in questions:
        writer.writerow([
            re.fullmatch(r"<b>Question \d+:</b> (.*)", q).group(1),
            re.fullmatch(r"<b>Answer:</b> (.*)", a).group(1)
        ])

现在您可以使用“基本”卡类型导入这些。此代码丢弃问题编号;我希望这不是太重要。

于 2018-10-19T14:15:16.313 回答