1

I have started to make an anagram solver with Python, but since I was using a lot of words (every word in the English dictionary), I didn't want them as an array in my Python file and instead had them in a separate text file called dictionaryArray2.txt.

I can easily import my text file and display my words on the screen using Python but I cannot find a way to select a specific element from the array rather than displaying them all.

When I do print(dictionary[2]) it prints the second letter of the whole file rather than the second element of the array. I never get any errors. it just doesn't work.

I have tried multiple things but they all have the same output.

My code below:

f = open("dictionaryArray2.txt", "r")
dictionary = f.read()
f.close()

print(dictionary[2])
Will
  • 45
  • 6
  • `f.read()` just gives you all of the content in the file as a string. Any index in that string gives you a character. If you want to read the lines of the file... use `.readlines()`. – jonrsharpe Jan 21 '20 at 22:21
  • Ahh, I was wondering what .readlines() did. Thanks for clearing that up for me. – Will Jan 21 '20 at 22:27
  • Have you done any research, read any guides/tutorials or the documentation? _from the array_ How do you know it's an array? You really should use a context manager to handle the file object, by the way. – AMC Jan 21 '20 at 23:55
  • This is a duplicate of https://stackoverflow.com/q/3277503/11301900. – AMC Jan 21 '20 at 23:57
  • @AMC I've not done a lot no, but I have had a look around – Will Jan 22 '20 at 17:31

2 Answers2

0

If you want to split the content of dictionaryArray2 into separate words, do:

f = open("dictionaryArray2.txt", "r")
dictionary = f.read()
f.close()

print(dictionary[2])

If you want to split the content of dictionaryArray2 into separate lines, do:

f = open("dictionaryArray2.txt", "r")
dictionary = f.readlines()
f.close()

words = dictionary.split()
print(words[2])
ProteinGuy
  • 1,754
  • 2
  • 17
  • 33
0

I think the problem is, you're reading the entire file into a single long list. If your input dictionary is one word per line, I think what you want is to get a text file like this:

apple
bat

To something like this:

dictionary = ['apple', 'bat']

There's an existing answer that might offer some useful code examples, but in brief, f.read() will read the entire file object f. f.readlines(), on the other hand, iterates over each line one at a time.

To quote from the official Python docs:

If you want to read all the lines of a file in a list you can also use list(f) or f.readlines().

Jim J
  • 546
  • 3
  • 11
  • Originally I did have it as one word per line, only I had quotes around each word as if each one was a string in the array. But this answer does clear that up. Thank you – Will Jan 21 '20 at 22:31