首页 > 解决方案 > 如何遍历文件的每一行并打印出任何包含两个相邻元音的单词?

问题描述

这是我尝试过的。但我收到一条错误消息:

错误:<re.Match 对象;跨度=(74, 76),匹配='ai'>

程序应该打印出任何包含两个连续元音的单词。Text.txt 文件内容:

text = "This is a test file with a single word per line. Print any words that contain two vowels next to each other."   a = text.split(" ").rstrip("\n")  
my_file = open("test.txt", "w")

Python代码:

   reg = r"[aeiou][aeiou]"
with open("text.txt") as f:
    for word in f:
        word = word.strip()
        print(re.search(reg, word, re.I))     

标签: python

解决方案


你可以这样经历:

import re
with open('test.txt') as f:
  for line in f:
    line = line.strip()
    if re.search(r"[aeiou][aeiou]",line,re.I):
      print(line)

推荐阅读