如何在Python中清理`sqlite_master`格式?

huangapple go评论60阅读模式
英文:

How do I clean up `sqlite_master` format in Python?

问题

Your Python application appears to be creating SQLite3 tables and printing debugging information. The output you provided has formatting issues with tabs (\t), newline characters (\n), and excessive whitespace. It seems you want to clean up this formatting.

Here is the cleaned-up output:

SQL - Sqlite3 Information
====================================

Sqlite3 Version: 3.11.0 

(u'table', u'Music', u'Music', 2, u'CREATE TABLE Music(Id INTEGER PRIMARY KEY, OsFileName TEXT, OsAccessTime FLOAT, OsModificationTime FLOAT, OsCreationTime FLOAT, OsFileSize INT, MetaArtistName TEXT, MetaAlbumName TEXT, MetaSongName TEXT, ReleaseDate FLOAT, OriginalDate FLOAT, Genre TEXT, Seconds INT, Duration TEXT, PlayCount INT, TrackNumber TEXT, Rating TEXT, UnsynchronizedLyrics BLOB, LyricsTimeIndex TEXT)') 

(u'index', u'OsFileNameIndex', u'Music', 3, u'CREATE UNIQUE INDEX OsFileNameIndex ON Music(OsFileName)') 

(u'table', u'History', u'History', 4, u'CREATE TABLE History(Id INTEGER PRIMARY KEY, Time FLOAT, MusicId INTEGER, User TEXT, Type TEXT, Action TEXT, SourceMaster TEXT, SourceDetail TEXT, Target TEXT, Size INT, Count INT, Seconds FLOAT, Comments TEXT)') 

(u'index', u'MusicIdIndex', u'History', 5, u'CREATE INDEX MusicIdIndex ON History(MusicId)') 

(u'index', u'TimeIndex', u'History', 6, u'CREATE INDEX TimeIndex ON History(Time)') 

(u'index', u'TypeActionIndex', u'History', 7, u'CREATE INDEX TypeActionIndex ON History(Type, Action)')

If you have any further questions or need assistance with anything else, please let me know.

英文:

My Python application is nearing completion (for three years) and I'm adding debugging information:

print("\nSQL - Sqlite3 Information")
print("====================================\n")

print("Sqlite3 Version:", sql.sqlite3.sqlite_version, "\n")
rows = sql.con.execute("SELECT * FROM sqlite_master;").fetchall()
for row in rows:
    print(row, "\n")

The output is strange with tab (\t) and newline (\n) characters plus extraordinary amount of whitespace:

SQL - Sqlite3 Information
====================================

Sqlite3 Version: 3.11.0 

(u'table', u'History', u'History', 7, u'CREATE TABLE History(Id INTEGER PRIMARY KEY,                 Time FLOAT, MusicId INTEGER, User TEXT, Type TEXT,                 Action TEXT, SourceMaster TEXT, SourceDetail TEXT,                 Target TEXT, Size INT, Count INT, Seconds FLOAT,                 Comments TEXT)') 

(u'index', u'MusicIdIndex', u'History', 15, u'CREATE INDEX MusicIdIndex ON                 History(MusicId)') 

(u'index', u'TimeIndex', u'History', 28, u'CREATE INDEX TimeIndex ON                 History(Time)') 

(u'table', u'Music', u'Music', 1277, u'CREATE TABLE "Music" (\n\t`Id`\tINTEGER,\n\t`OsFileName`\tTEXT,\n\t`OsAccessTime`\tFLOAT,\n\t`OsModificationTime`\tFLOAT,\n\t`OsCreationTime`\tFLOAT,\n\t`OsFileSize`\tINT,\n\t`MetaArtistName`\tTEXT,\n\t`MetaAlbumName`\tTEXT,\n\t`MetaSongName`\tTEXT,\n\t`ReleaseDate`\tFLOAT,\n\t`OriginalDate`\tFLOAT,\n\t`Genre`\tTEXT,\n\t`Seconds`\tINT,\n\t`Duration`\tTEXT,\n\t`PlayCount`\tINT,\n\t`TrackNumber`\tTEXT,\n\t`Rating`\tTEXT,\n\t`UnsynchronizedLyrics`\tBLOB,\n\t`LyricsTimeIndex`\tTEXT,\n\tPRIMARY KEY(Id)\n)') 

(u'index', u'OsFileNameIndex', u'Music', 2, u'CREATE UNIQUE INDEX OsFileNameIndex ON                 Music(OsFileName)\n\n') 

(u'index', u'TypeActionIndex', u'History', 16, u'CREATE INDEX TypeActionIndex ON                 History(Type, Action)') 

Am I making a rookie mistake when creating the Sqlite3 tables in Python?

    """ Open SQL Tables """
    global con, cursor, hist_cursor
    # con = sqlite3.connect(":memory:")  # Initial tests, not needed anymore
    con = sqlite3.connect(FNAME_LIBRARY)

    # MUSIC TABLE - 'PlayCount' & 'Rating' not used
    
    # Create the table (key must be INTEGER not just INT !
    # See https://stackoverflow.com/a/7337945/6929343 for explanation
    con.execute("create table IF NOT EXISTS Music(Id INTEGER PRIMARY KEY, \
                OsFileName TEXT, OsAccessTime FLOAT, \
                OsModificationTime FLOAT, OsCreationTime FLOAT, \
                OsFileSize INT, MetaArtistName TEXT, MetaAlbumName TEXT, \
                MetaSongName TEXT, ReleaseDate FLOAT, OriginalDate FLOAT, \
                Genre TEXT, Seconds INT, Duration TEXT, PlayCount INT, \
                TrackNumber TEXT, Rating TEXT, UnsynchronizedLyrics BLOB, \
                LyricsTimeIndex TEXT)")

    con.execute("CREATE UNIQUE INDEX IF NOT EXISTS OsFileNameIndex ON \
                Music(OsFileName)")


    # HISTORY TABLE
    con.execute("create table IF NOT EXISTS History(Id INTEGER PRIMARY KEY, \
                Time FLOAT, MusicId INTEGER, User TEXT, Type TEXT, \
                Action TEXT, SourceMaster TEXT, SourceDetail TEXT, \
                Target TEXT, Size INT, Count INT, Seconds FLOAT, \
                Comments TEXT)")

    con.execute("CREATE INDEX IF NOT EXISTS MusicIdIndex ON \
                History(MusicId)")
    con.execute("CREATE INDEX IF NOT EXISTS TimeIndex ON \
                History(Time)")
    con.execute("CREATE INDEX IF NOT EXISTS TypeActionIndex ON \
                History(Type, Action)")

Success Using Variation of Accepted Answer:

SQL - Sqlite3 Information
====================================

Sqlite3 Version: 3.11.0 

(u'table', u'Music', u'Music', 2, u'CREATE TABLE Music(Id INTEGER PRIMARY KEY, OsFileName TEXT, OsAccessTime FLOAT, OsModificationTime FLOAT, OsCreationTime FLOAT, OsFileSize INT, MetaArtistName TEXT, MetaAlbumName TEXT, MetaSongName TEXT, ReleaseDate FLOAT, OriginalDate FLOAT, Genre TEXT, Seconds INT, Duration TEXT, PlayCount INT, TrackNumber TEXT, Rating TEXT, UnsynchronizedLyrics BLOB, LyricsTimeIndex TEXT)') 

(u'index', u'OsFileNameIndex', u'Music', 3, u'CREATE UNIQUE INDEX OsFileNameIndex ON Music(OsFileName)') 

(u'table', u'History', u'History', 4, u'CREATE TABLE History(Id INTEGER PRIMARY KEY, Time FLOAT, MusicId INTEGER, User TEXT, Type TEXT, Action TEXT, SourceMaster TEXT, SourceDetail TEXT, Target TEXT, Size INT, Count INT, Seconds FLOAT, Comments TEXT)') 

(u'index', u'MusicIdIndex', u'History', 5, u'CREATE INDEX MusicIdIndex ON History(MusicId)') 

(u'index', u'TimeIndex', u'History', 6, u'CREATE INDEX TimeIndex ON History(Time)') 

(u'index', u'TypeActionIndex', u'History', 7, u'CREATE INDEX TypeActionIndex ON History(Type, Action)') 

Snippet of Code used:

    # MUSIC TABLE - 'PlayCount' & 'Rating' not used
    # Avoid \t & \n in sqlite_master. See: https://stackoverflow.com/questions/76427995/
    # how-do-i-clean-up-sqlite-master-format-in-python
    # Create the table (key must be INTEGER not just INT !
    # See https://stackoverflow.com/a/7337945/6929343 for explanation
    con.execute("create table IF NOT EXISTS Music(Id INTEGER PRIMARY KEY, " +
                "OsFileName TEXT, OsAccessTime FLOAT, " +
                "OsModificationTime FLOAT, OsCreationTime FLOAT, " +
                "OsFileSize INT, MetaArtistName TEXT, MetaAlbumName TEXT, " +
                "MetaSongName TEXT, ReleaseDate FLOAT, OriginalDate FLOAT, " +
                "Genre TEXT, Seconds INT, Duration TEXT, PlayCount INT, " +
                "TrackNumber TEXT, Rating TEXT, UnsynchronizedLyrics BLOB, " +
                "LyricsTimeIndex TEXT)")

    con.execute("CREATE UNIQUE INDEX IF NOT EXISTS OsFileNameIndex ON " +
                "Music(OsFileName)")

答案1

得分: 2

Sure, here are the translated parts of the text you provided:

  1. "plus extraordinary amount of whitespace" -> "加上大量的空白"

  2. "There's other ways to phrase that." -> "还有其他表达方式。"

  3. "Here is one, similar to the original but without \ backwhacks." -> "这是一个,与原始版本类似但没有\转义字符。"

  4. "Notice that we have \n newlines thrown in there, now." -> "请注意,现在我们有\n换行符在其中。"

  5. "Here is another way." -> "这是另一种方式。"

  6. "Fewer \n newlines in that one, and less whitespace." -> "这个版本中\n换行符较少,空白也较少。"

  7. "In general, given some sql command, you can always squish out extra whitespace:" -> "一般来说,给定某个sql命令,你总是可以压缩额外的空白:"

  8. "Of course some sql WHERE clauses won't survive that naive approach, such as sql = "... WHERE text like '%two spaces%'"." -> "当然,一些 SQL WHERE 子句不会在这种简单的方法下生效,比如 sql = "... WHERE text like '%two spaces%'"。"

  9. "A very convenient method of removing leading whitespace from a """string""" is to use dedent()." -> "从三重引号字符串中删除前导空白的一种非常方便的方法是使用 dedent()。"

  10. "from textwrap import dedent" -> "from textwrap import dedent"

  11. "s = """\n... one\n... two\n... """" -> "s = """\n... one\n... two\n... """"

  12. "print(s, dedent(s))" -> "print(s, dedent(s))"

Please note that I've retained the HTML entities (e.g., ") in the translated text as they are used for special characters and should be preserved.

英文:

> plus extraordinary amount of whitespace

Well, you did send in quite a large amount of whitespace.

    con.execute("create table IF NOT EXISTS History(Id INTEGER PRIMARY KEY, \
                Time FLOAT, ... , Type TEXT, \
                Action TEXT, ... , SourceDetail TEXT, \

There's other ways to phrase that.
Here is one, similar to the original but without \ backwhacks.

    con.execute("""
        create table ... KEY,
        Time FLOAT, ... , Type TEXT,
        Action TEXT, ... , SourceDetail TEXT, ...
    """)

Notice that we have \n newlines thrown in there, now.

Here is another way.

    con.execute(
        "create table ... KEY,"
        " Time FLOAT, ... , Type TEXT,"
        " Action TEXT, ... , SourceDetail TEXT, ..."
    )

Fewer \n newlines in that one, and less whitespace.

In general, given some sql command, you can always
squish out extra whitespace:

    def squish(s: str) -> str:
        return " ".join(s.split())

    con.execute(squish(sql))

Of course some sql WHERE clauses won't survive that
naïve approach, such as sql = "... WHERE text like '%two spaces%'".


A very convenient method of removing leading whitespace
from a """string""" is to use
dedent().

>>> from textwrap import dedent
>>> 
>>> s = """
...    one
...    two
... """
>>> 
>>> print(s, dedent(s))

   one
   two
 
one
two

>>> 

</details>



huangapple
  • 本文由 发表于 2023年6月8日 09:03:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76427995.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定