1

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.

wovano
  • 4,543
  • 5
  • 22
  • 49
alxnom334
  • 33
  • 4

1 Answers1

1

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())
ScottC
  • 3,941
  • 1
  • 6
  • 20