2012-01-15 44 views
6

多個部分我有一個數據庫:拆分可變長度字符串轉換成在python

正如你可以在「說明」一欄看到,該文本是可變長度(意味着沒有兩個字符串我的從這個數據庫拉將會是相同的長度)。我最終會在這個數據庫中添加更多條目,但這是我正在測試的內容,現在開始。

現在,我有以下Python代碼搶串的這些塊,並顯示它們:

cmd = input(Enter command:) 
sql = "SELECT cmd,`desc` FROM table WHERE cmd = '"+ cmd +"'" 
cursor.execute(sql) 
result = cursor.fetchall() 
for row in result: 
    print("Command: "+ row[0] +":\n") 
    print("Description: "+ row[1][:40] +"\n") 
    if (len(row[1]) > 40): 
     print(row[1][40:85]) 
    if (len(row[1]) > 85): 
     print(row[1][85:130]) 
    if (len(row[1]) > 130): 
     print(row[1][130:165]) 
    if (len(row[1]) > 165): 
     print(row[1][165:]) 

這裏的拆分工作到一定程度,例如:

命令:關閉:
說明:該命令將在調用char
acter的消息窗口中創建'close',但將生成
n。如果當前沒有窗口在屏幕上,那麼腳本執行將結束。

正如您在上面的輸出示例中看到的那樣,分割會導致某些字符在中間詞中被截斷。鑑於這些字符串的長度可能在20個字符之間,最多爲190個字符之間,我想將字符串分成幾塊......每個字8個字,因爲空間限制,我將如何去關於這樣做?

+0

使用參數替換而不是手動構建sql字符串,例如'cursor.execute('select * from cmd =?',(cmd,))''。你不需要調用'cursor.fetchall()'你可以直接遍歷它:'對於遊標中的行:...' – jfs 2012-01-16 00:18:13

回答

2

將空格拆分以分隔單詞,然後每次連接8個空格作爲分隔符。

content = "This is some sentence that has more than eight words" 
content = content.split(" ") 
print content 
['This', 'is', 'some', 'sentence', 'that', 'has', 'more', 'than', 'eight', 'words'] 
print(" ".join(content[0:8])) 
This is some sentence that has more than 
+0

謝謝!這就是我現在正在尋找的東西。 – Jguy 2012-01-15 23:30:06

1

削減使用python textwrap模塊的詞代替字符:

>>> import textwrap 
>>> text = 'asdd sdfdf asdsg asfgfhj' 
>>> s = textwrap.wrap(text, width=10) # <- example 10 characters 
>>> s 
['asdd sdfdf', 'asdsg', 'asfgfhj'] 
>>> print '\n'.join(s) 
asdd sdfdf 
asdsg 
asfgfhj 
>>> 
16

退房的textwrap module

>>> import textwrap 
>>> 
>>> s = "This command will create a 'close' button in the message window for the invoking character. If no window is currently on screen, the script execution will end." 
>>> 
>>> wrapped = textwrap.wrap(s, 40) 
>>> 
>>> for line in wrapped: 
...  print line 
... 
This command will create a 'close' 
button in the message window for the 
invoking character. If no window is 
currently on screen, the script 
execution will end. 

你可以做很多TextWrapper的配置。

+0

TIL textwrap,非常有用 – JustinDanielson 2012-01-15 23:19:41

+0

這存在嗎?! Python標準庫永遠不會讓我感到驚訝。 +1 – senderle 2012-01-15 23:22:07

+0

我正在研究一個骯髒的伎倆來完成工作。我不知道這樣的東西是可用的。一旦我有機會,我一定會看看。謝謝! – Jguy 2012-01-15 23:28:35