简体   繁体   中英

Printing out filenames of txt.-files that include at least one line of words, each starting with vowels. Only 1 line of code

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.

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM