如何在Python中获取根词?

时间:2015-04-01 07:57:49

标签: python

我想得到一个词的根源。我没有使用词干分析器,因为我只是想做一些替换。这是我的代码;它给了我正确的结果,但是当一个标记以“ies”结尾时它不会用“y”替换“ies”:

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]

3 个答案:

答案 0 :(得分: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]

答案 1 :(得分:1)

string.replace() returns a new string;它不会更新原始的。您只需将结果存储在print之前:

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

答案 2 :(得分:1)

string.replace没有改变原来的object。它只返回被替换的string。所以存储到另一个variable进行进一步的操作。或者如果你想要打印,那么只需

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

但如果您想要替换last ies,如果存在另一个ies,则此解决方案无效。

例如

In [27]: token = "anyiesifies"

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