簡體   English   中英

按字符位置列表拆分字符串

[英]Split a string by list of character positions

假設你有一個字符串:

text = "coding in python is a lot of fun"

和字符位置:

positions = [(0,6),(10,16),(29,32)]

這些是區間,分別涵蓋文本中的某些詞,即編碼、python 和樂趣。

使用字符位置,你怎么能分割這些詞上的文本,得到這個 output:

['coding','in','python','is a lot of','fun']

這只是一個示例,但它應該適用於任何字符串和任何字符位置列表。

我不是在尋找這個:

[text[i:j] for i,j in positions]

我會將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', ''] ,所以它需要一些額外的工作來去除空格

下面的代碼按預期工作

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)

Output: ['coding', 'in', 'python', 'is a lot', 'fun']

注意:如果不需要空間,您可以修剪它們

暫無
暫無

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

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