簡體   English   中英

使用Python中的SQLite3數據庫處理文本

[英]Processing text from SQLite3 Database in Python

我有一個SQLite3數據庫,其中包含日語文本的句子和稱為假名的其他字符,這有助於語音閱讀。

我有一個函數remove_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))

Python SQLite fetchall函數返回一個由該記錄中的字段組成的元組。 您需要將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結果將是字典,您可以訪問content字段:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM