【问题标题】:Converting a file in list format into a dictionary with multiple conditions. (python)将列表格式的文件转换为具有多个条件的字典。 (Python)
【发布时间】:2021-04-25 08:22:37
【问题描述】:

免责声明,抱歉,如果我没有明确表达我的问题。术语对我来说仍然是新事物。提前感谢您的阅读。

好的,我有一个名为

的函数
def pluralize(word)

目的是使文件中的所有名词复数。我想要的输出是: {'plural': word_in_plural, 'status' : x} word_in_plural 是输入参数 (word) 的复数形式,而 x 是可以具有以下值之一的字符串; 'empty_string'、'proper_noun'、'already_in_plural'、'success'。

到目前为止,我的代码看起来像..


filepath = '/proper_noun.txt'

def pluralize(word):
  proper_nouns = [line.strip() for line in open (filepath)]     ### reads in file as list when function is called
  dictionary = {'plural' : word_in_plural, 'status', : x}       ### defined dictionary 
    if word == '':                                              ### if word is an empty string, return values; 'word_in_plural = '' and x = 'empty_string'
      dictionary['plural'] = ''
      dictionary['status'] = 'empty_string'
      return dictionary

您在上面看到的是我尝试编写一个条件,如果单词是空字符串,则返回指定的值。

下一个目标是创建一个条件,如果 word 已经是复数形式(假设它以 's' 'es' 'ies' .. 等结尾),则该函数返回一个字典具有以下值:**word_in_plural = word 和 x = 'already_in_plural'。所以输入的词保持不变。例如。 (输入:公寓,输出:公寓)

    if word ### is already in plural (ending with plural), function returns a dictionary with values; word_in_plural = word and x = 'already_in_plural' 
      

关于如何读取字符串的最后一个字符以实现规则的任何想法?我也很怀疑这个逻辑。

感谢您对 SOF 社区的投入。

【问题讨论】:

    标签: python dictionary if-statement conditional-statements


    【解决方案1】:

    您可以通过 -1 对单词进行索引以获取其最后一个字符。您可以对字符串进行切片以获取最后两个 [-2:] 或最后三个 [-3:] 字符

    last_char = word[-1]
    last_three_char = word[-3:]
    

    【讨论】:

    • 目标是将所有可能的复数形式的单词匹配到每个字符串的末尾。它适用于默认参数,但在考虑所有可能性时。我想知道是否有一种聪明的方法可以做到这一点。可能是我想多了。
    • 您可以使用如下条件语句: if word[-1] == "s" or word[-2:] == "es" or word[-3:] == "ies " 或......当然,它不会捕捉到像“geese”这样的不规则复数,并且会错误地将像“Mars”这样的单词算作胸膜。要真正捕捉复数,您需要更复杂的算法和英文复数字典。
    • 是的,pakpe,我实现了这些想法。我用 [-1] == s 做了一个强有力的假设。它更多的是实现逻辑而不是合法的多元化。
    猜你喜欢
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    • 2016-12-27
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    相关资源
    最近更新 更多