import re
twovowels=re.compile(r".*[aeiou].*[aeiou].*", re.I)
nonword=re.compile(r"\W+", re.U)
text_file = open("twoVoweledWordList.txt", "w")
file = open("FirstMondayArticle.html","r")
for line in file:
for word in nonword.split(line):
if twovowels.match(word): print word
text_file.write('\n' + word)
text_file.close()
file.close()
这是我的 python 代码,我试图只打印出现两个或多个元音的单词。当我运行这段代码时,它会将所有内容(包括没有元音的单词和数字)打印到我的文本文件中。但是 python shell 向我显示了所有出现两个或多个元音的单词。那我该如何改变呢?
请您参考如下方法:
您可以使用 str.translate 删除元音并比较长度。如果删除字母后长度差 > 1,则您至少有两个元音:
with open("FirstMondayArticle.html") as f, open("twoVoweledWordList.txt", "w") as out:
for line in file:
for word in line.split():
if len(word) - len(word.lower().translate(None,"aeiou")) > 1:
out.write("{}\n".format(word.rstrip()))
在您自己的代码中,您总是将单词写为 text_file.write('\n' + word) 位于 if block 之外。关于为什么你不应该在一行中有多个语句的一个很好的教训,你的代码相当于:
if twovowels.match(word):
print(word)
text_file.write('\n' + word) # <- outside the if
带有 if 的代码位于正确的位置,对命名约定进行了一些更改,在赋值之间添加了一些空格并使用 with 为您关闭文件:
import re
with open("FirstMondayArticle.html") as f, open("twoVoweledWordList.txt", "w") as out:
two_vowels = re.compile(r".*[aeiou].*[aeiou].*", re.I)
non_word = re.compile(r"\W+", re.U)
for line in f:
for word in non_word.split(line):
if two_vowels.match(word):
print(word)
out.write("{}\n".format(word.rstrip()))
