2017-02-13 148 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

相关问题