My task is to write only one line of code in python. The code should do the following: I need to print out filenames of txt.files, which include at least one line of words, starting with only vowels (each word needs to start with a vowel from at least one line). My code is:
[filename for filename in listdir(".")if filename.endswith('.txt') and [line for line in open(filename) if ([word for word in line.split() if word[0] in ['a','e','i','o','u']])]]
I tried to use os.listdir, but i am not allowed to write more than one sentence. My code also prints all 3 of my txt.files, even if one text file doesn´t include a sentence with words, which all start with vowels. Thank you for your time and the help before.
CodePudding user response:
You could try the following one-liner:
print([filename for filename in os.listdir(".") if filename.endswith('.txt') and [line for line in open(filename) if all(word.startswith(('a','e','i','o','u','A','E','I','O','U')) for word in line.split())]])
OUTPUT:
['file3.txt']
Test files
Tested with file1.txt
, file2.txt
and file3.txt
.
file1.txt:
The quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog
file2.txt:
A quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog
file3.txt:
The quick brown fox jumps over the lazy dog
Orangutangs appreciate apples over oranges and apricots
Note
You can also use:
all((word[0] in 'aeiouAEIOU') for word in line.split())
instead of
all(word.startswith(('a','e','i','o','u','A','E','I','O','U')) for word in line.split())