【问题标题】:Pluralize word in python在python中复数单词
【发布时间】: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 文件和所有问题。

question file

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。

标签: python string function


【解决方案1】:

我觉得删除就够了:

for i in range(len(wordsStorage)):
    wordsStorage[i] = wordsStorage[i][:-1] 

这个循环用没有最后一个字母的单词覆盖wordsStorage 中的每个单词。例如,zulma 转换为 zulm

因此word.lower() in wordsStorage 为假,如果word 包含"zulma",因为"zulm" 在列表中。

【讨论】:

  • 已经试过了,不行
  • 是否可以显示proper_nouns.txt 中的一些示例行?我假设,名词用新行分隔
  • proper_nouns.txt 包含各种名称。全部以小写字母开头
  • 它们是如何分开的?使用新行或逗号或其他内容?
  • 刚刚在下面添加了链接
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-26
  • 2014-11-06
  • 2023-04-03
  • 2018-07-26
  • 2013-09-23
  • 1970-01-01
  • 2013-10-21
相关资源
最近更新 更多