1

I'm trying to create a list on python from a text file saved in my documents. The list contains the 1000 most commonly used words in the english dictionary, with each word on a new line in the text file.

When I tried doing:

wordlist = []

with open("C:\\Users\\Myname\\Documents\\words.txt") as file:
    for line in file:
        wordlist.append(line)

print(wordlist)

The result I got was:

['the\n', 'of\n', 'to\n', 'and\n', 'a\n', 'in\n', 'is\n', 'it\n', 'you\n', 'that\n', 'he\n', 'was\n', 'for\n', 'on\n', 'are\n'....etc.]

I would like each element/word in the list to be without the quotation marks and the \n.

The second part to my question is how can I choose a random word from either that created list in python, or from the .txt file directly (in fact I'd like to learn how to do both) and save it to a variable?

Edit: also, how can I choose a random word over a certain number of characters from either that created list in python, or from the .txt file directly

I am running the latest version of python

3 Answers3

0

You can do this to your first question:

lista = ['the\n', 'of\n', 'to\n', 'and\n', 'a\n', 'in\n', 'is\n', 'it\n', 
 'you\n', 'that\n', 'he\n', 'was\n', 'for\n', 'on\n', 'are\n']

listaAux = ['\n']
trans = {ord(i): '' for i in listaAux}
lista = [j.translate(trans) for i in lista for j in i]

print(lista)

For the second question... you can use this lib..

     import random

and do this:

lista_word = ['oi','ae','ui']
word = random.choice(lista_word)
print (word)
0

You need the quotation marks since these delimit the string values. After you load the wordlists, you can do simply:

Python 3.6
Type "help", "copyright", "credits" or "license" for more information.

import random
wordlist = []
with open("C:\\Users\\Myname\\Documents\\words.txt") as file:
    for line in file:
        wordlist.append(line)
wordlist = list(map(lambda x : x[:-1], wordlist))
print(random.choice(wordlist))
  • Yep it works for printing a random word from the list. Is there any way though to only choose a random word over a certain number of characters/letters? – SNIPERATI0N Oct 08 '17 at 04:47
  • It is better to split a single post with multiple questions to several posts. This way it is easier to help. Now, your last question is duplicated. See: https://stackoverflow.com/questions/26697601/python-return-elements-of-list-that-have-certain-length – Victor Polo De Gyves Montero Oct 08 '17 at 05:19
0

For removing the newline character from each string you can use:

wordlist = []

with open("C:\\Users\\Myname\\Documents\\words.txt") as file:
    for line in file:
        wordlist.append(line.strip('\n'))

print(wordlist)

And for choosing any random string your list you can simply use 'random'

import random
print(random.choice(wordList))
Avik Aggarwal
  • 599
  • 7
  • 28