2017-02-13 134 views
-3

我需要讀取一個文本文件,並找出第一個字母.txt文件的句子中的每個單詞是否是元音。我有這個至今:獲取句子中每個單詞的第一個字母?

def main(): 
#Open, read and close the datafile 
datafile=open(input('Enter File Name: ')) 
contents=datafile.read() 
datafile.close 

def startsWithVowel(): 
    if contents[0] in ['A','a','E','e','I','i','O','o','U','u']: 
     return true 
    else: 
     return false 

該檢查數據文件的內容的第一個字母,但我需要檢查在句子中的每一個字,但我不知道如何在每個單詞的第一個字母工作一句話。請幫忙!

+0

你想在什麼時候返回True?當所有行的所有單詞都以一個元音開始?對我來說似乎沒有用處。 –

+3

找出誰在phyton中分割一個字符串。將字符串拆分爲空格。在每個單詞上運行循環以檢查它是否以元音開頭 – Filype

+2

如果您想忽略標點符號,數字和其他字符,將內容拆分爲單詞可能會很困難。一個天真的做法是'contents.split()'。 – martineau

回答

3

在你main功能與contents = datafile.readlines()替換contents=datafile.read(),然後相應地改變你的startsWithVowel爲:

def startsWithVowel(): for i in contents: if i[0] in ['A','a','E','e','I','i','O','o','U','u']: return True return False

也閉上你的文件作爲datafile.close()和使用TrueFalse代替truefalse的蟒蛇。

4
VOWELS = set(['a', 'e', 'i', 'o', 'u']) 


def starts_with_vowel(word): 
    # make code more clean and efficient 
    return word[0].lower() in VOWELS 


# open the file using context manager - no need to do implicit open/close 
with open(input('Enter File Name: ')) as f: 
    for line in f: # for every line in the file f 
     for word in line.split(" "): # split the line into word 
      print(starts_with_vowel(word)) 
+2

僅有代碼的答案很少有用。你有機會寫出一個好的答案,不要浪費它。 –

+0

非常感謝。所以對於這段代碼,我使用readlines還是隻讀? –

+0

這段代碼對於f中的每一行的f - >行都有效。也爲你打開並關閉文件。 – etlsh

相關問題