简体   繁体   English

打印出包含至少一行单词的 txt. 文件的文件名,每个单词都以元音字母开头。 仅1行代码

[英]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).我的任务是在 Python 中只写一行代码。代码应该执行以下操作: 我需要打印出 txt.files 的文件名,其中至少包含一行单词,仅以元音开头(每个单词需要以至少有一行的元音)。 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.我尝试使用os.listdir() ,但不允许我写超过一句话。 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.我的代码还打印了我的所有 3 个 txt.files,即使一个文本文件不包含一个句子,所有单词都以元音开头。

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: OUTPUT:

['file3.txt']



Test files测试文件

Tested with file1.txt , file2.txt and file3.txt .使用file1.txtfile2.txtfile3.txt进行测试。

file1.txt:文件 1.txt:

The quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog

file2.txt:文件2.txt:

A quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog

file3.txt:文件 3.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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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