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