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.
You can use itertools (for permutations) and regular expressions (for searching)
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']
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?
精彩评论