[英]Split string elements of a list with multiple separators/conditions. Any good Python library?
[英]Converting a file in list format into a dictionary with multiple conditions. (python)
免責聲明,對不起,如果我沒有明確表達我的問題。 術語對我來說仍然是新事物。 提前感謝您的閱讀。
好吧,我有一個名為 function
def pluralize(word)
目的是使文件中的所有名詞復數。 我想要的 output 是:{'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'.. 等結尾),則 function 返回一個字典,其值如下:**word_in_plural = word and x = 'already_in_plural'。 所以輸入的詞保持不變。 例如。 (輸入:公寓,output:公寓)
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 社區的投入。
您可以通過 -1 索引單詞以獲取其最后一個字符。 您可以對字符串進行切片以獲取最后兩個 [-2:] 或最后三個 [-3:] 字符
last_char = word[-1]
last_three_char = word[-3:]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.