Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中获取根单词?_Python - Fatal编程技术网

如何在Python中获取根单词?

如何在Python中获取根单词?,python,Python,我想找到一个词的词根。我没有使用词干分析器,因为我只是想做一些替换。这是我的密码;它给出了正确的结果,但当令牌以“ies”结尾时,它不会将“ies”替换为“y”: string.replace();它不会更新原始版本。您只需在打印前存储结果即可: token = string.replace(token,'ies','y',1) string.replace没有更改原始的对象。它只返回被替换的字符串。因此存储到另一个变量以进行进一步的操作。或者,如果要打印,只需 if token.endswi

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

string.replace()
;它不会更新原始版本。您只需在打印前存储结果即可:

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

string.replace
没有更改原始的
对象
。它只返回被替换的
字符串
。因此存储到另一个
变量
以进行进一步的操作。或者,如果要打印,只需

if token.endswith("ies"):
    print string.replace(token, 'ies', 'y', 1)
但是,如果您想在存在另一个
ies
的情况下替换
最后一个
ies
,则此解决方案不起作用

例如

In [27]: token = "anyiesifies"

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

为了给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]

值得注意的是,即使您重新分配
令牌
,也只会在循环中影响该字符串。不修改列表中的值。
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]