2010-08-04 116 views
3

我想解析一個字符串以獲取包含所有單詞(帶連字符的單詞)的列表。當前的代碼:Python正則表達式字符串到單詞列表(包括帶連字符的單詞)

s = '-this is. A - sentence;one-word' 
re.compile("\W+",re.UNICODE).split(s) 

回報:

['', 'this', 'is', 'A', 'sentence', 'one', 'word'] 

,我想它返回:

['', 'this', 'is', 'A', 'sentence', 'one-word'] 
+0

爲什麼你喜歡的「」? – 2010-08-04 19:39:19

回答

1

你可以使用"[^\w-]+"代替。

+0

這將返回' - 這個',但我知道沒有更好的解決方案。我覺得沒有辦法再一次回過頭來去除不必要的缺點。 – 2010-08-04 15:01:00

0

呦可以與NLTK庫嘗試:

>>> import nltk 
>>> s = '-this is a - sentence;one-word' 
>>> hyphen = r'(\w+\-\s?\w+)' 
>>> wordr = r'(\w+)' 
>>> r = "|".join([ hyphen, wordr]) 
>>> tokens = nltk.tokenize.regexp_tokenize(s,r) 
>>> print tokens 
['this', 'is', 'a', 'sentence', 'one-word'] 

我在這裏找到:http://www.cs.oberlin.edu/~jdonalds/333/lecture03.html希望它可以幫助

4

如果您不需要主導空字符串,你可以使用該模式爲\w(?:[-\w]*\w)?匹配

>>> import re 
>>> s = '-this is. A - sentence;one-word' 
>>> rx = re.compile(r'\w(?:[-\w]*\w)?') 
>>> rx.findall(s) 
['this', 'is', 'A', 'sentence', 'one-word'] 

注意與像012撇號,它將不匹配的話。

+0

謝謝,它的工作 – Sibish 2015-04-06 09:58:11

1

s = "-this is. A - sentence;one-word what's"
re.findall("\w+-\w+|[\w']+",s)

結果: [ '這個', '是', 'A', '一句話', '一個字', 「什麼是」]

確保您注意到正確的排序是先查找hyypenated的單詞!

2

這裏我傳統的「爲什麼要使用正則表達式語言時,你可以使用Python的」另類:

import string 
s = "-this is. A - sentence;one-word what's" 
s = filter(None,[word.strip(string.punctuation) 
       for word in s.replace(';','; ').split() 
       ]) 
print s 
""" Output: 
['this', 'is', 'A', 'sentence', 'one-word', "what's"] 
""" 
相關問題