简体   繁体   中英

How do I loop through each line of a file and print out any words that contain two vowels next to each other?

This is what I tried. But I got an error message:

Error: <re.Match object; span=(74, 76), match='ai'>

The program should print out any words that contain two consecutive vowels. Text.txt file content:

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

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

you can go through like this:

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)

You can do this without a regex as well:

with open(ur_file) as f:
    for line in f:
        for x,y in zip(line,line[1:]):
            if all(e.lower() in 'aeiou' for e in (x,y)):
                print(line.rstrip())
                break

Also:

import re
words = "This is a test file with a single word per line. Print any words that contain two vowels next to each other.".split()
print([w for w in words if re.match(r".*[aeiouy][aeiouy].*",w)])

For a small number of words, you could create a list of all two-vowel pairs and check if any of them are in your target word. This reads a little cleaner than the other solutions, but is likely much less performant.

def has_vowel_pair(word):
    vowels = 'aeiouy'
    vowel_pairs = {x+y for x in vowels for y in vowels} + {y+x for x in vowels for y in vowels}
    return any(pair in word for pair in vowel_pairs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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