Home > Enterprise >  Python re.match word count
Python re.match word count

Time:11-29

I want to find and print all states that start with M and contain i or I only once. I tried to find M contain states first and count the i sequence..

import re
pattern = 'i'
state_names=['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut',
'Delaware','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana',
'Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts',
'Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada',
'New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio',
'Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee',
'Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin',
'Wyoming']
m_word=['']

for k in range (len(state_names)):
  state=state_names[k]
  mword=m_word[k]
  mword.append(re.search('^M',state))

  left = 0
  count = 0
  while True:
      match = re.search(pattern, mword)
      if not match:
          break
      count  = 1
      left  = match.start()   1
      for i in range (len(m_word)):
          if (count==1):
              print(mword[i])
  print(count)

CodePudding user response:

That's a lot of code for the task - I'd do something simpler, like:

m_states = [state for state in state_names if state[0] == "M"]
answers = [m_state for m_state in m_states if m_state.count("i")   m_state.count("I") == 1]

EDIT: thanks for the comment Pedro - updated:

m_states = [state for state in state_names if state.startswith("M")]
answers = [m_state for m_state in m_states if m_state.lower().count("i") == 1]

CodePudding user response:

Regular expression will make it necessarily more complicated. Here is the simple solution.

>>> state_names=['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut',
... 'Delaware','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana',
... 'Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts',
... 'Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada',
... 'New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio',
... 'Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee',
... 'Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin',
... 'Wyoming']
>>> 
>>> for word in state_names:
...     if word.startswith('M'):
...             letters = [ l.lower() for l in word]
...             if letters.count('i')==1:
...                     print(word)
... 
Maine
Minnesota
>>> 
  • Related