tracy
tracy

Reputation: 1

searching in python

I am trying to search a file to find all words which use any or all of the letters of a persons first name and are the same length as their first name. I have imported the file and it can be opened and read etc, but now i want to be able to seach the file for any words which would contain the specified letters, the words have to be same length as the persons first name.

Upvotes: 0

Views: 599

Answers (3)

Jonas Byström
Jonas Byström

Reputation: 26169

def find_anagrams_in_file(filename, searchword):
    import re
    searchword = searchword.lower()
    found_words = []
    for line in open(filename, 'rt'):
        words = re.split(r'\W', line)
        for word in words:
            if len(word) == len(searchword):
                tmp = word.lower()
                try:
                    for letter in searchword:
                        idx = tmp.index(letter)
                        tmp = tmp[:idx] + tmp[idx+1:]
                    found_words += [word]
                except ValueError:
                    pass
    return found_words

Run as so (Python 3):

>>> print(find_anagrams_in_file('apa.txt', 'Urne'))
['Rune', 'NurE', 'ERUN']

Upvotes: 1

Michal Chruszcz
Michal Chruszcz

Reputation: 2490

I would approach this problem this way:

  • filter out the words of the length different from the length of the first name,
  • iterate over the rest of the words checking whether intersection of first name's letters and word's letters is non-empty (set might be useful here).

P.S. Is that your homework?

Upvotes: 0

Don
Don

Reputation: 17606

You can use itertools (for permutations) and regular expressions (for searching)

Upvotes: 1

Related Questions