2016-12-27 57 views
-5

傢伙,我知道我已經問了一個非常相似,但我要瘋了.....獨立字符串在Python

我有一個字符串:

string = '☕ Drink the ❶ best ☕coffee☕' 

我期待這樣的:

string = ['☕', 'Drink', 'the', '❶', 'best', '☕', 'coffee', '☕'] 
+0

你試圖匹配的字母和其他非'空間「字符? – Tushar

+1

你有沒有嘗試除了期待? – DeepSpace

+0

SO不是免費的編碼服務! – Fallenhero

回答

1

您可以使用正則表達式:

import re 

s = [el for el in re.split('([\W+])', '☕ Drink the ❶ best ☕coffee☕') if el.strip()] 
print(s) 

輸出:

['☕', 'Drink', 'the', '❶', 'best', '☕', 'coffee', '☕'] 
+0

親愛的上帝thx發送我neverwalkaloner ....! – dapo

+0

@dapo歡迎您:) – neverwalkaloner

0

您可以使用ord找到一個字符的順序。如果它高於126,則在Unicode區域內,它位於ASCII之上。

import itertools 
s = '☕ Drink the ❶ best ☕coffee☕' 

for k,v in itertools.groupby(s, lambda c: ord(c)<127): 
    for word in ''.join(v).split(): 
     print(word) 

結果:

☕ 
Drink 
the 
❶ 
best 
☕ 
coffee 
☕ 

注:我寫這一個文件,如終端往往具有較差的Unicode處理:

>>> with open(r'theoutput.txt', 'w', encoding='utf-8-sig') as output: 
...  for k,v in itertools.groupby(s, lambda c: ord(c)<127): 
...    for word in ''.join(v).split(): 
...      print(word, file=output) 
... 
>>>