Saturday, 15 August 2015

python - Removing \n from myFile -



python - Removing \n from myFile -

i trying create dictionary of list key anagrams , value(list) contains possible words out of anagrams.

so dict should contain this

{'aaelnprt': ['parental', 'paternal', 'prenatal'], ailrv': ['rival']}

the possible words within .txt file. every word separated newline. example

sad dad fruit pizza

which leads problem when seek code it.

with open ("word_list.txt") myfile: word in myfile: if word[0] == "v": ##interested in word starting "v" word_sorted = ''.join(sorted(word)) ##get anagram keys in list(dictonary.keys()): if keys == word_sorted: ##heres problem, doesn't within here theres characters in <word_sorted> possible "\n" due linebreak of myfi print(word_sorted) dictonary[word_sorted].append(word)

if every word in "word_list.txt" followed '\n' can utilize slicing rid of lastly char of word.

word_sorted = ''.join(sorted(word[:-1]))

but if lastly word in "word_list.txt" isn't followed '\n', should utilize rstrip().

word_sorted = ''.join(sorted(word.rstrip()))

the piece method more efficient, applicaton uncertainty you'll notice difference, might play safe & utilize rstrip().

python anagram

No comments:

Post a Comment