假設你有一個字串:
text = "coding in python is a lot of fun"
和字符位置:
positions = [(0,6),(10,16),(29,32)]
這些是區間,分別涵蓋了文本中的某些單詞,即編碼、python 和 fun。
使用字符位置,您如何拆分這些單詞上的文本,以獲得以下輸出:
['coding','in','python','is a lot of','fun']
這只是一個示例,但它應該適用于任何字串和任何字符位置串列。
我不是在找這個:
[text[i:j] for i,j in positions]
uj5u.com熱心網友回復:
我壓扁positions是[0,6,10,16,29,32],然后像做
positions.append(-1)
prev_positions = [0] positions
words = []
for begin, end in zip(prev_positions, positions):
words.append(text[begin:end])
這個確切的代碼產生['', 'coding', ' in ', 'python', ' is a lot of ', 'fun', ''],所以它需要一些額外的作業來去除空白
uj5u.com熱心網友回復:
下面的代碼按預期作業
text = "coding in python is a lot of fun"
positions = [(0,6),(10,16),(29,32)]
textList = []
lastIndex = 0
for indexes in positions:
s = slice(indexes[0], indexes[1])
if positions.index(indexes) > 0:
print(lastIndex)
textList.append(text[lastIndex: indexes[0]])
textList.append(text[indexes[0]: indexes[1]])
lastIndex = indexes[1] 1
print(textList)
輸出:['coding', 'in', 'python', 'is a lot of ', 'fun']
注意:如果不需要空間,您可以修剪它們
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/388747.html
上一篇:Python字串格式的區別
下一篇:strcat&覆寫
