用Python处理SQLite3数据库中的文本

2024-09-26 22:54:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个SQLite3数据库,其中包含日语文本的句子和附加字符furigana,有助于语音阅读。你知道吗

我有一个函数,remove\u furigana,它可以处理一个字符串并返回没有furigana字符的字符串。但是,当我传递这个函数时,从数据库中提取的句子似乎没有任何效果。有人能为我澄清一下这里发生了什么,并为我指出解决问题的方向吗?你知道吗

def remove_furigana(content):
    furigana = False
    expression = ""
    for character in content:
        if character == '[':
            furigana = True
        elif character == ']':
            furigana = False
        elif not furigana:
            expression += character
    return expression.replace(" ", "")

def retrieve_article():
    c.execute('SELECT content FROM sentence WHERE article_id = "k10010770581000"')
    for row in c.fetchall():
        print(remove_furigana(row))

Tags: 函数字符串in数据库falsefordefcontent
1条回答
网友
1楼 · 发布于 2024-09-26 22:54:52

pythonsqlite fetchall function返回由该记录中的字段组成的元组。您需要将content列发送到函数:

def retrieve_article():
    c.execute('SELECT content FROM sentence WHERE article_id = "k10010770581000"')
    for row in c.fetchall():
        print(remove_furigana(row[0]))

或者,可以使用row_factory获取字典而不是元组:

import sqlite3

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

con = sqlite3.connect(":memory:") con.row_factory = dict_factory

在这种情况下,fetchall结果将是dictionary,您可以访问content字段,如下所示:

    print(remove_furigana(row['content']))

相关问题 更多 >

    热门问题