How to select a random word from a txt file in python version 3.4? - python-3.4

**
I have a txt file called 'All_Words' and it consist of 2000 words and i'm making a hangman so i needed to choose a random word i've already thought of picking a random number from 0 to 2000 and read the line of the number to chose but i don't know how to do that, also some background info:
i am in 8th grade and i like coding im trying to get better so i'm trying to get what people suggest and try to figure out what every part does and the reserved words such as 'global' for example
also i have also tried to just shuffle the txt file because i already got it to print the first word so if im a able to shuffle the txt file then it would print a different word an i could create an if statement saying if the word chosen was already chooses then it would shuffle it again and pick he first word again, also i got this idea of the shuffle the txt file from my dad but he only did something called 'dos' or something like that he said he did it before it was even called coding so i don't even know if it world word in python, and i've asked my coding teacher and he said he dont know how you would do that because he is use to java and javascript
this is what i have so far and also i would like it to only pick one word instead of every word in order:**
import random
with open("All_Words.txt") as file:
for line in file:
print(line)
break

Assuming each word is on a new line in file, you can read the text file into a list and use random.choice() to pick a random element in the list. Then you remove the word from the list so you don't pick it again.
import random
file = open("All_Words.txt", "r")
words = file.read()
listOfWords = words.split("\n")
randWord = random.choice(listOfWords)
print(randWord)
listOfWords.remove(randWord)
newUnqiueRandWord = random.choice(listOfWords)
print(newUnqiueRandWord)

Related

Optimized way to write a series strings to a text file without quotations

I am new to Julia so sorry if this question is obvious.
I am trying to use Julia to help me run a series of finite element models, which use a text input file to give instructions to the finite element solver. Basically, I would like to use Julia to read in the base input file, edit some parameters on some lines of the file and then write it as a new file. I am getting hung up on a couple things though.
Currently, I am reading in the file like this
mdl = "fullmodelSVTV"; #name of input file
A = readlines(mdl*".inp")
This read each line from the file in as a separate string in a vector which I like because it makes it easier to edit the sections I want but it also makes things more difficult when I try to write to a new file.
I am writing the file like this.
io = open("name.inp","w")
print(io,A)
close(io)
When I try to write to a new file the output ends up look like this
Output from code
which is ["string at index 1","string at index 2","string at index 3"...].
What I would like to do is output this the exact same way is it is read in with string at each index of the vector on its own line. I would also like to remove the brackets and quotation marks from the file, as they might interfere with the finite element solver.
I think I have found a way to concatenate all of the strings at each index and separated them with a new line like shown below.
for i in 1:length(A)
conc = conc*"\n"*lines[i]
end
The issue with this is that it takes a long time to do given the size of the input files I am working with and I feel like there has to achieve my goal.
I also cannot find a way to remove the brackets or quotation marks when writing the file.
So, I'm wondering if anyone has any advice for a better way to write these text files in terms of both concatenating all of the strings from the vector when outputting as well as outputting without the brackets and quotation marks.
Thanks, any advice is appreciated.
The issue with print(io,A) is that it is printing a representation of the vector, but in fact you want to print each element of the vector. To do so, you can simply print each line in a loop:
open("name.inp", "w") do io
for line in A
println(io, line)
end
end
This avoids the overhead of string concatenation.

Lyx. Space between letters of some words in program listing

When I create a pdf document that I'm writing in Lyx, there are spaces between letters in some words when I use code programs to insert some pieces of programming.
In the Lyx program listing configuration I added the option "showstringspaces = false" but I do not get anything.
Can you tell me how I can remove these annoying spaces so that all the letters of each word in the code lists appear together?
I get ---> fmt. P r i n t
I expect ---> fmt.Print
I answer to myself. Putting the option columns = fullflexible or columns = flexible in the configuration of the code lists is solved

R write over only first few lines of a file

Hi I want to do something that I thought should be simple but can't seem to find a way. I have some files I want to change something in the heading lines, given by a key word. The lines I want to change are always in the first 20 lines, but not necessarily exactly the same line number.
So I want to read in the first 20 lines (which is easy), find and change my string (again easy) and then write over the top 20 lines of the file and keep the thousands of rows below without changing. I'm going to have to do this hundreds and hundreds of times thus why I don't want to read in the entire file and write it all.
I have created a very simplified example. WARNING I'm creating a file called Temp.txt in your current working directory if you run this.
#Create Dummy text file
write.table(file = "Temp.txt", data.frame(Test = letters[1:26]), row.names = F, quote = F)
And then I can read in the lines and change
# read top 5 lines of text file (In real life I need to look at 20, but for examples sake 2)
TestHeader = readLines("Temp.txt", n = 5)
# Find and replace my search string
TestHeader[grepl("c",TestHeader)] <- "My New Line"
# <what to do here?> I want to only write over first 20 lines
Obviously I can read in the entire thing and change
TestHeader = readLines("Temp.txt")
TestHeader[grepl("c",TestHeader)] <- "My New Line"
writeLines(TestHeader, "Temp.txt")
But this would involve unnecessarily reading and writing thousands and thousands of lines.

R: Extract value and lines after key word (text file mining)

Setting:
I have (simple) .csv and .dat files created from laboratory devices and other programs storing information on measurements or calculations. I have found this for other languages but nor for R
Problem:
Using R, I am trying to extract values to quickly display results w/o opening the created files. Hereby I have two typical settings:
a) I need to read a priori unknown values after known key words
b) I need to read lines after known key words or lines
I can't make functions such as scan() and grep() work.
c) Finally I would like to loop over dozens of files in a folder and give me a summary (to make the picture complete: I will manage this part)
I woul appreciate any form of help.
ok, it works for the key value (although perhaps not very nice)
variable<-scan("file.csv", what=character(),sep="")
returns a charactor vector of everything
variable[grep("keyword", ks)+2] # + 2 as the actual value is stored two places ahead
returns characters of seaked values.
as.numeric(lapply(variable, gsub, patt=",", replace="."))
for completion: data had to be altered to number and "," and "." problem needed to be solved.
in a line:
data=as.numeric(lapply(ks[grep("Ks_Boden", ks)+2], gsub, patt=",", replace="."))
Perseverence is not to bad of an asset ;-)
The rest isn't finished, yet, I will post once finished.

Is there a way to check the spelling of words in a character vector?

The text to be checked is in Greek, but I would like to know if it can be done for English words too. My initial idea is described here, and I have already found a way to do it using VBA. But I wonder if there's a way to do it using R. If there isn't a way in R, do you think of something better than Excel-vba?
Alternatively, OpenOffice ships with a dictionary that entries stored in a text file. You can read that and remove the word definitions to create your word list.
This was tested on v3.0; the file location may have shifted, and the filename will change depending on which dictionary you want.
library(stringr)
dict <- readLines("C:/Program Files/OpenOffice.org 3/share/uno_packages/cache/uno_packages/174.tmp_/dict-en.oxt/th_en_US_v2.dat")
is_word <- str_detect(dict, "^[^(]")
words <- str_split_fixed(dict[is_word], "\\|", 2)
words <- words[,1]
This list contains some multi-word phrases. You may prefer to split on the first space, and take unique values. You probably also want to write words to file, to save repeating yourself.
Once this is done, checking a word is as easy as
c("persnickety", "sqwrzib") %in% words # TRUE FALSE
There exists an open source GNU spell checker called Aspell with suppot for various languages. This is a command line program which I basically use for scanning bunches of text files at once (then the output is just given to the console).
But there also exists a C API and perhaps more interesting for you a Pipe mode which accepts streams of texts and outputs to the standard output.
Hope this helps.

Resources