2016-10-18 29 views
0

stackoverfollowers! 我有,我不能打擊到年底列表中的字符串中的文本行中的單詞。如何返回必需的輸出?

任務編寫一個函數words(a, b, txt)

txt = ['All in the golden afternoon\nFull leisurely we glide;\nFor both our oars, with little skill,\nBy little arms are plied,\nWhile little hands make vain pretence\nOur wanderings to guide.']

a = 6

b = 8

一個函數將返回所有每行的長度爲6到8個字母的文字 。如果一行沒有這樣的單詞,則返回空字符串 。如果某行有多個單詞,他們應該有一個訂單 像他們有一條線

功能words(a,b,txt)應該返回

['golden', '', 'little','little', 'little pretence', '']

我已經寫了這樣的代碼:

def noalpha(s): 


    noa = ''   # choose all non-alphabetic symbols 
    for c in s: 
     if not (c in noa or c.isalpha()): 
      noa += c 
    return noa 

def words(a,b,txt): 

    lst = [] 
    for i in txt:  # work with a whole text that is one element in list txt 

     i = i.splitlines() # split text in lines \n 
     for s in i:   # iteration in lines 
      s = s.split() 
      for w in s:  # iteration in words 
       w = w.replace(noalpha(w), '') 

       if a <= len(w) <= b: 
        lst.append(w) 


     return lst 

所以我找不到方法:

  1. 回報''(空字符串)爲一整行不包含必要的長度
  2. 的話,如果一個行包含一個以上的字我不能像'word1 word2 word3'
+1

您是否正確縮進了最終的「返回」?輸出是否正確,當你分開單詞時,你如何返回「小句子」?你可以'return''.join(lst)'將字作爲字符串返回。 – AChampion

+0

順便說一句:你有什麼問題,因爲它似乎返回預期的輸出。 – AChampion

+0

我的函數返回列表像這樣['golden','little','little','little','pretense']但它應該像這樣返回['golden','','little','little', '小假裝',''] 所以我沒有投票字符串和單詞'小'和'僞裝'分別返回,而需要返回他們在一個字符串,因爲他們屬於同一行 –

回答

0

喜歡的東西歸還這個?

def alpha(word): 
    return ''.join(char for char in word if char.isalpha()) 


result = [] 
for line in txt[0].splitlines(): 
    words = [alpha(word) for word in line.split()] 
    result.append(' '.join(word for word in words if a <= len(word) <= b)) 
相關問題