![](/img/trans.png)
[英]How do I loop through each line of a file and print out any words that contain two vowels next to each other?
[英]Printing out filenames of txt.-files that include at least one line of words, each starting with vowels. Only 1 line of code
我的任务是在 Python 中只写一行代码。代码应该执行以下操作: 我需要打印出 txt.files 的文件名,其中至少包含一行单词,仅以元音开头(每个单词需要以至少有一行的元音)。 我的代码是:
[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']])]]
我尝试使用os.listdir()
,但不允许我写超过一句话。 我的代码还打印了我的所有 3 个 txt.files,即使一个文本文件不包含一个句子,所有单词都以元音开头。
您可以尝试以下单行:
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']
使用file1.txt
、 file2.txt
和file3.txt
进行测试。
文件 1.txt:
The quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog
文件2.txt:
A quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog
文件 3.txt:
The quick brown fox jumps over the lazy dog
Orangutangs appreciate apples over oranges and apricots
您还可以使用:
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.