1
#!/usr/bin/env python

import sys
import re

# regular expressions

pattern = re.compile("[a-zA-Z]*",
                 re.MULTILINE | re.DOTALL | re.IGNORECASE)

# Read pairs as lines of input from STDIN
for line in sys.stdin:

    # loop through every word that matches the pattern
    for word in pattern.findall(line):
        while i < 1:
            if len(converted_word) != WINDOW:
                # print "word =", word
                if a_to_f_pattern.match(word[i]):
                   .....

            else:
               .....
        i = 0

this line here

if a_to_f_pattern.match(word[i]):

gives me the error in title and i cannot figure out why

previously, i had while i < len(word) and it worked but now because i want to only check the first letter of each word it does not work.

any clues?

7
  • Is your pattern matching an empty string? Commented Apr 26, 2016 at 20:44
  • ah no it reads words from text files. Commented Apr 26, 2016 at 20:46
  • Add print word to your loop. Commented Apr 26, 2016 at 20:47
  • hold on, hmm it seems you are right, i thought my pattern only took letters. Commented Apr 26, 2016 at 20:47
  • * means zero or more of whatever matches the preceding expression, so it will match zero letters. Use + instead to match at least 1. Commented Apr 26, 2016 at 20:48

1 Answer 1

1

The regular expression [a-zA-Z]* will match an empty string, because * means "zero or more". Use [a-zA-Z]+ instead to ensure that your words are at least one letter long.

Also, since you're using re.IGNORECASE, you don't need to put both uppercase and lowercase letters in the pattern. And there's no need for the re.MULTILINE option if the pattern doesn't contain ^ or $, and no need for re.DOTALL if there's no . in the pattern. So it should just be:

pattern = re.compile("[a-z]+", re.IGNORECASE)
Sign up to request clarification or add additional context in comments.

2 Comments

hmm just tried this but it gives me duplicate words?
If the input line has duplicate words, the regexp will return them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.