2016-03-03 126 views
2

我使用Python中下面的代碼字符串分割成單詞主題標籤的第n次出現前:分割字符串在python

keywords=re.sub(r'[][)(!,;]', ' ', str(row[0])).split() 

想象中的輸入是:

"Hello #world I am in #London and it is #sunny today" 

我需要它僅在出現第二個#標籤和之前分開文字,不需要分開其餘的,這意味着輸出應該是:

['Hello','#world','I','am','in'] 

是否有任何解決方案在Python中以這種方式將字符串拆分爲關鍵字?

+1

你的拆分也對空白在結果 – Oz123

回答

3

str.find需要一個起始位置,所以當你發現第一次使用該索引+1噸開始尋找第二個,然後拆分子:

s = "Hello #world I am in #London and it is #sunny today" 
i = s.find("#", s.find("#") + 1) 
print(s[:i].split()) 
['Hello', '#world', 'I', 'am', 'in'] 

你也可以做同樣的搭配指數:

s = "Hello #world I am in #London and it is #sunny today" 
i = s.index("#", s.index("#") + 1) 
print(s[:i].split()) 

如果子字符串不存在,則作爲索引的區別將引發錯誤。

3

split方法接受一個字符來分割,否則它會分割空白。在終端

string_to_split = "Hello #world I am in #London and it is #sunny today" 
# Split on all occurrences of # 
temp = string_to_split.split("#") 
# Join the first two entries with a '#' and remove any trailing whitespace 
temp_two = '#'.join(temp[:2]).strip() 
# split on spaces 
final = temp_two.split(' ') 

運行:

>>> string_to_split = "Hello #world I am in #London and it is #sunny today" 
>>> temp = string_to_split.split("#") 
>>> temp_two = '#'.join(temp[:2]).strip() 
>>> final = temp_two.split(' ') 
>>> final 
['Hello', '#world', 'I', 'am', 'in'] 

編輯:固定[2:]到[2]我總是讓他們混在一起

編輯:固定的多餘的空格問題

+0

非常感謝你,我認爲這個答案更接近我需要的東西,只是我不確定它是否是最佳的,考慮到大量字符串作爲輸入的時間複雜性? – Far

2

interactive python:

>>> str="Hello #world I am in #London and it is #sunny today" 
>>> hash_indices=[i for i, element in enumerate(str) if element=='#'] 
>>> hash_indices 
[6, 21, 39] 
>>> str[0:hash_indices[1]].split() 
['Hello', '#world', 'I', 'am', 'in'] 
>>> str[hash_indices[1]:] 
'#London and it is #sunny today' 
>>> 
1

正則表達式和分裂

source = "Hello #world I am in #London and it is #sunny today" 
reg_out = re.search('[^#]*#[^#]*#', source) 
split_out = reg_out.group().split() 
print split_out[:-1] 

O/P: '你好', '#world', '我', '上午', '中']