我想使用Python和NLTK工作,但似乎無法使用正則表達式對他們來說,不能找出原因。Python的正則表達式的錯誤:「不能分配給操作」
>>> import nltk
>>> import re
>>> words = nltk.corpus.words.words('en')
>>> ed-words = [w for w in words if re.search('ed$', w)]
SyntaxError: can't assign to operator
我想使用Python和NLTK工作,但似乎無法使用正則表達式對他們來說,不能找出原因。Python的正則表達式的錯誤:「不能分配給操作」
>>> import nltk
>>> import re
>>> words = nltk.corpus.words.words('en')
>>> ed-words = [w for w in words if re.search('ed$', w)]
SyntaxError: can't assign to operator
正如其他人所說,在變量名中使用-
是相當多的違法大多數編程語言。
在Python中,你可以使用下劃線:
ed_words = [w for w in words if re.search('ed$', w)]
非常感謝。我覺得這是一個愚蠢的想法。 –
這裏的問題是ed-words
:Python中的-
符號就是去掉,所以它試圖處理ed - words = ...
,這是違法的。
不能使用'-'變量名......它被加工成'ed' *負*'words' *等於* ...使用下劃線分隔單詞...查看:HTTP:/ /docs.python.org/2/reference/lexical_analysis.html#identifiers我還會注意到在你的用例中,使用'if w.endswith('ed')'作爲你的過濾條件更簡單。 –
我只能回想起Lisp的計算機語言,其中包含'-'的變量名是合法的。 –