【发布时间】:2022-01-04 20:50:33
【问题描述】:
我正在编写一个必须使单词复数的函数。对于以大写 Z -> Zulma 开头的单词,我的输出应该是
Zulma --> {'plural': 'Zulma', 'status': 'proper_noun'}
而我的是:
Zulma --> {'plural': 'Zulmas', 'status': 'success'}
last elif或is last else中的代码有错误
在两个附件中,我附上了 .txt 文件和所有问题。
def pluralize(word):
wordsStorage = []
x = ''
word_in_plural = ''
with open("proper_nouns.txt", "r") as file:
wordsStorage = file.readlines()
file.close()
for i in range(len(wordsStorage)):
wordsStorage[i] = wordsStorage[i][:-1]
if word == '':
x = 'empty_string'
word_in_plural = 'plural'
return {word_in_plural: '', "status": x}
elif word[-1] == 's':
word_in_plural = word
x = 'already_in_plural'
return {word_in_plural: word, "status": x}
elif word.lower() in wordsStorage:
word_in_plural = word
x = 'proper_noun'
return {word_in_plural: word, "status": x}
else:
if word[-1] == 'a' or word[-1] == 'e' or word[-1] == 'i' or word[-1] == 'o' or word[-1] == 'u':
word_in_plural = word + 's'
elif word[-1] == 'y' and word[-2] != 'a' and word[-2] != 'o' and word[-2] != 'i' and word[-2] != 'e' and word[-2] != 'u':
word_in_plural = word[:-1] + 'ies'
elif word[-1] == 'f':
word_in_plural = word[:-1] + 'ves'
elif word[-2:] == 'sh' or word[-2:] == 'ch' or word[-2:] == 'z':
word_in_plural = word + 'es'
else:
word_in_plural = word + 's'
x = "success"
return {"plural": word_in_plural, "status": x}
#pass
TEST_CASES = """
Zulma""".split('\n')
if __name__ == '__main__':
for test_noun in TEST_CASES:
print(test_noun,'-->',pluralize(test_noun))
print('----')
【问题讨论】:
-
为什么你应该以
proper_noun为例,代码在产生这个结果时哪里出错了? -
欢迎来到 Stack Overflow!请使用tour 并阅读How to Ask。你有什么问题?您可以edit 澄清。如果您正在寻找调试帮助,您需要创建一个minimal reproducible example,包括最少的代码。
-
我强烈建议您逐行调试代码。 PyCharm 是一个免费的 Python IDE,具有出色的调试器。使用方法如下:jetbrains.com/help/pycharm/…
-
如果
proper_nouns.txt包含 Zulma,那么word.lower() in wordsStorage将为 false。