【发布时间】:2014-06-30 01:58:11
【问题描述】:
给定一个文本文件“words.txt”,使用列表推导读入文件中的所有单词,找出所有至少包含 2 个元音的单词。
所以,我有一个文本文件:
The quick brown fox jumps over the lazy dog
而且,获取所有单词以及所有具有两个或多个元音的单词的最佳尝试是:
#This could be hardcoded in, but for the sake of simplicity (as simple as simplicity gets)
vowels = ["a","e","i","o","u"]
filename = "words.txt"
words = [word for word in open(filename, "r").read().split()]
multivowels = [each for each in open(filename, "r").read().split() if sum(letter in vowels for letter in each) >= 2]
输出应该模仿:
All words in the file: ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
The words in the file that contain 2 or more vowels: ['quick', 'over']
我试图把它放在一行中只是打印“单词”和“多元音”的列表理解侧以及“文件中的所有单词;”......等等。
有没有人挑战将这两个列表推导合二为一?我和我的队友很困惑,但很想向我们的教授炫耀!
我最后的单行代码是:
print "All words in the file: " + str([word for word in open(filename, "r").read().split()]) + "\nAll words with more than 2 vowels: " + str([each for each in open(filename, "r").read().split() if sum(letter in vowels for letter in each) >= 2])
编辑: 我尝试获取文件中的所有单词,以及包含两个或多个元音的所有单词。
vowels = ["a", "e", "i", "o", "u"]
filename = "words.txt"
print [(word, each) for word in open(filename, "r").read().split() if sum([1 for each in word if each in vowels]) >= 2]
【问题讨论】:
-
为什么要写成一行?它使 FAR 的调试和可读性变得更加困难
-
我不会读两次文件。
-
您的教授是否对您让其他人解决问题表示赞赏?
-
写成一行的原因只是为了向我的教授证明我可以战胜他的挑战。毫无疑问,这绝对是一种可怕的编码方式。但是,他挑战我这样做,所以我至少要尝试一下!这只是为了好玩。我只是想看看是否有人有任何见解。
-
可以使用
.seek(0)重置已经打开的文件
标签: python file list-comprehension word