2015-04-01 71 views
-4

我想獲取單詞的根。我沒有使用stemmer,因爲我只是想做一些替換。這是我的代碼;它給了我正確的結果,但它並不能取代「的IE」與「Y」當令牌「IES」結尾:如何在Python中獲取根詞?

import string; 
contents = ["shoping", "balls", "babies"] 
for token in contents: 
    if token.endswith("ies"): 
     string.replace(token,'ies','y',1) 
     print token 
    elif token.endswith('s'): 
     print token[0:-1] 
    elif token.endswith("ed"): 
     print token[0:-2] 
    elif token.endswith("ing"): 
     print token[0:-3] 

回答

1

string.replace()returns a new string;它不更新原來的一個。您只需將結果存儲print之前荷蘭國際集團它:

token = string.replace(token,'ies','y',1) 
+1

值得一提的是,即使你重新分配'token',僅影響該字符串,而你的循環是。列表中的值未被修改。 – Blckknght 2015-04-01 08:04:22

+0

哦,確定它運作良好 – 2015-04-01 08:04:45

1

string.replace沒有改變原來的object。它只有返回更換string。所以店裏另一variable進一步manipulations.Or如果你要打印,然後簡單地

if token.endswith("ies"): 
    print string.replace(token, 'ies', 'y', 1) 

但這個解決方案沒有工作,如果你想更換lasties如果存在另一個ies

例如

In [27]: token = "anyiesifies" 

In [28]: string.replace(token, 'ies', 'y', 1) 
Out[28]: 'anyyifies' 
2

要添加多一點GoBusto的答案,使用字符串庫是多餘的(以及進口字符串後的分號)。

你可以這樣做,而不是:

contents = ["shoping", "balls", "babies"] 
for token in contents: 
    if token.endswith("ies"): 
     token = token.replace('ies','y',1) 
     print token 
    elif token.endswith('s'): 
     print token[0:-1] 
    elif token.endswith("ed"): 
     print token[0:-2] 
    elif token.endswith("ing"): 
     print token[0:-3]