I am trying to write a program that queries a word document and returns a line randomly from that document. Currently, every line from the document is being returned, even when I apply random.choice(). Any thoughts on how I can correct this?
I ran a len() on my list and confirmed it is returning multiple variables, but the entire list is still being returned.
import random
filename = 'happy document.txt'
dictionary_list = []
with open(filename) as file_object:
lines = file_object.readlines()
for l in lines:
lines = [l.strip('\n') for l in lines]
dictionary_list.append(lines)
random_choice = random.choice(dictionary_list)
print(random_choice)
You append the whole list of lines to your dictionary_list on each loop, so whichever of its items you choose, it's the whole list...
You can do:
import random
filename = 'happy document.txt'
with open(filename) as file_object:
lines = [line.strip('\n') for line in file_object]
random_choice = random.choice(lines)
print(random_choice)
As a side note, for line in file_object iterates on the lines of the file, you don't need to use readlines first and iterate again on the list of lines.
You want
dictionary_list.extend(lines)
to "un-nest" the lines into your dictionary_list.
Related
Full Problem: I have a text file that is made of different sequences on each line, I need to print to the user specifict lines individually.
File Example:
title(line1)
ywzcywczywwyczwyczwyczywwwyzczczyw(line2)
title2(line3)
yxzwyxzwyxwyxzwywyxzwyxwyxzwy(line4)
title3(line5)
ywzxywxzywywxzywxywyzxywxz(line6)
--In this example, I would need to print lines 2,4, and 6 to the user but one by one. (meaning I don't want to print all those lines at once.)
I have the following code to read the file:
f = open("File.txt", "r") #open file and "r" is to read the file
I was thinking of reading the file and creating two different lists (One that will include all the titles as individual elements of the list and another one that will include all the "sequences"(ywxzwyzyxw) as individual element of the list, and then somehow printing each element of the desired list Individually, (instead of printing all the list at ones)
I'm new to python so I'm looking for example code that would help me tackle this problem.
Thank you!!
You should think if a pattern to determine the titles like . title or x title or 1. title etc. Then you can use if else statement to identify the title.
file:
.title1
sequence1
.title2
sequence2
code:
with open("file.txt", "r") as f:
all_lines = f.readlines()
titles = []
sequences = []
for line in all_lines:
if "." in line[0]:
titles.append(line.rstrip("\n"))
all_lines.remove(line)
for lines in all_lines:
sequences.append(lines.rstrip("\n"))
print(titles)
print(sequences)
You can also use caharacter numbers to identify. Like if every title is less than 8 characters long and the sequences are much longer then you can use the len() function the determine if the line is title or not.
file:
title1
sequence1
title2
sequence2
code:
with open("file.txt", "r") as f:
all_lines = f.readlines()
titles = []
sequences = []
for line in all_lines:
if len(line)<8:
titles.append(line.rstrip("\n"))
all_lines.remove(line)
for lines in all_lines:
sequences.append(lines.rstrip("\n"))
print(titles)
print(sequences)
Then to print each element of the desired list individually:
for elements in titles:
print(elements)
or
for elements in sequences:
print(elements)
If you have some kind of pattern you may use,
with open(filename) as file:
lines = file.readlines()
for i, line in enumerate(lines): #i is the index for every element.
if i % 2 == 1:
continue
else:
print(line)
In this example, we are just going to print the lines like 0,2,4,6 etc.
I have a file that includes a list of every zip code, city, and state in the US. When I read a list it looks like " '00501', 'Huntsville', 'NY' ".
So what I'm trying to do in Python is:
Open the file, read everysingle line, split the lines, then create 3 new lists Zip, City, State and place all the data from the original list into the new lists.
So far, I have the following code:
def main():
zipcode = []
city = []
state = []
file_object = open("zipcodes.txt", "r")
theList = file_object.readlines()
splitlist = theList.split(',')
zipcode.append(splitlist[0])
city.append(splitlist[1])
state.append(splitlist[2])
file_object.close()
You have the basics, you are just missing a loop so the process repeats for each line in the file:
theList = file_object.readlines()
for line in theList:
splitlist = line.split(',')
zipcode.append(splitlist[0])
city.append(splitlist[1])
state.append(splitlist[2])
Keep in mind that readlines() returns the entire file so your theList contains the entire file's contents. You just have to loop over it.
Here is a different version you can try:
def main():
zips = []
cities = []
states = []
with open('zipcodes.txt', 'r') as f:
for line in f:
bits = line.split(',')
zips.append(bits[0])
cities.append(bits[1])
states.append(bits[2])
The with_statement is a way to read files. It ensures that files are automatically closed.
The for line in f: loop is what you were missing in your code - this will go through each line.
The body of the for loop is exactly what you have written, so that part you had down well.
i want to generate a list of server addresses and credentials reading from a file, as a single list splitting from newline in file.
file is in this format
login:username
pass:password
destPath:/directory/subdir/
ip:10.95.64.211
ip:10.95.64.215
ip:10.95.64.212
ip:10.95.64.219
ip:10.95.64.213
output i want is in this manner
[['login:username', 'pass:password', 'destPath:/directory/subdirectory', 'ip:10.95.64.211;ip:10.95.64.215;ip:10.95.64.212;ip:10.95.64.219;ip:10.95.64.213']]
i tried this
with open('file') as f:
credentials = [x.strip().split('\n') for x in f.readlines()]
and this returns lists within list
[['login:username'], ['pass:password'], ['destPath:/directory/subdir/'], ['ip:10.95.64.211'], ['ip:10.95.64.215'], ['ip:10.95.64.212'], ['ip:10.95.64.219'], ['ip:10.95.64.213']]
am new to python, how can i split by newline character and create single list. thank you in advance
You could do it like this
with open('servers.dat') as f:
L = [[line.strip() for line in f]]
print(L)
Output
[['login:username', 'pass:password', 'destPath:/directory/subdir/', 'ip:10.95.64.211', 'ip:10.95.64.215', 'ip:10.95.64.212', 'ip:10.95.64.219', 'ip:10.95.64.213']]
Just use a list comprehension to read the lines. You don't need to split on \n as the regular file iterator reads line by line. The double list is a bit unconventional, just remove the outer [] if you decide you don't want it.
I just noticed you wanted the list of ip addresses joined in one string. It's not clear as its off the screen in the question and you make no attempt to do it in your own code.
To do that read the first three lines individually using next then just join up the remaining lines using ; as your delimiter.
def reader(f):
yield next(f)
yield next(f)
yield next(f)
yield ';'.join(ip.strip() for ip in f)
with open('servers.dat') as f:
L2 = [[line.strip() for line in reader(f)]]
For which the output is
[['login:username', 'pass:password', 'destPath:/directory/subdir/', 'ip:10.95.64.211;ip:10.95.64.215;ip:10.95.64.212;ip:10.95.64.219;ip:10.95.64.213']]
It does not match your expected output exactly as there is a typo 'destPath:/directory/subdirectory' instead of 'destPath:/directory/subdir' from the data.
This should work
arr = []
with open('file') as f:
for line in f:
arr.append(line)
return [arr]
You could just treat the file as a list and iterate through it with a for loop:
arr = []
with open('file', 'r') as f:
for line in f:
arr.append(line.strip('\n'))
filename:dictionary.txt
YAHOO:YHOO
GOOGLE INC:GOOG
Harley-Davidson:HOG
Yamana Gold:AUY
Sotheby’s:BID
inBev:BUD
code:
infile = open('dictionary.txt', 'r')
content= infile.readlines()
infile.close()
counters ={}
for line in content:
counters.append(content)
print(counters)
i am trying to import contents of the file.txt to the dictionary. I have searched through stack overflow but please an answer in a simple way (not with open...)
First off, instead of opening and closing the files explicitly you can use with statement for opening the files which, closes the file automatically at the end of the block.
Secondly, as the file objects are iterator-like objects (one shot iterable) you can loop over the lines and split them with : character. You can do all of these things as a generator expression within dict function:
with open('dictionary.txt') as infile:
my_dict = dict(line.strip().split(':') for line in infile)
I assume that you don't have semi-colons in your keys.
In that case you should:
#read lines from your file
lines = open('dictionary.txt').read().split('\n')
#create an empty dictionary
dict = {}
#split every lines at ':' and use the left element as a key for the right value
for l in lines:
content = l.split(':')
dict[content[0]] = content[1]
So what I'd like to do is to make all the lines lowercase and then use my part_list to search for all words matching in frys.txt and to append it to items. I'm having a lot of trouble creating a loop that goes through each word in the list and just actually finding the words in frys.txt. I'm even trying to find doubles if that is at all possible. But the main thing I want to be able to do is just find that the word exists and to append it to items if it does.
Any suggestions would be great!
items = []
part_list = ['ccs', 'fcex', '8-12', '8-15', '8-15b', '80ha3']
f = open("C:/Users/SilenX/Desktop/python/frys.txt", "r+")
searchlines = f.readlines()
f.close()
for n, line in enumerate(searchlines):
p = 0
if part_list[p] in line.split():
part_list[p] = part_list[p + 1]
parts = searchlines[n]
parts = parts.strip('\n')
items.append(parts)
print items
You're doing some complex stuff with enumeration that I really don't think is necessary, and it definitely looks like your inner "loop" isn't doing what you want (because as you've written it, it isn't a loop). Try this:
part_list = ['ccs', 'fcex', '8-12', '8-15', '8-15b', '80ha3']
items = []
f = open("C:/Users/SilenX/Desktop/python/frys.txt", "r") # Open the file
for line in f:
for token in line.lower().split(): # Loop over lowercase words in the line
if token in part_list: # If it's one of the words you're looking for,
items.append(token) # Append it to your list.
f.close()
print items
This will find all the words in the file that appear in your list. It will not identify words in your file that are attached to something else, like "ccs." or "fcex8-12". If you want that, you'll have to reverse the way the search works, so that you count how many times each word in part_list appears in the line rather than counting how many words in the line are in part_list.