I need to write a program that reads a text file and returns the median of the numbers in the file. I think I have a good idea of how to approach this, but I got an AttributeError when running my program.
My question is: how do I make one list for the numbers in the text file? There are a total of 15 numbers, split across 5 lines in the file:
10 20 30
40 50 60
90 80 70
11 22 13
14 14 20
what I thought to do to create a list was:
num_list = fv.readlines()
num_list = num_list.split()
I thought this would read through all the lines of the file, then I could use the split function to create a list of the numbers. Now that I got an AttributeError: 'list' object has no attribute 'split', I'm unsure of what to do.
Without a solid expected result I assume you want all numbers in one list.
You can create an empty list then use list.extend as you loop through the file. You will need to cast them to int though. map is great for this:
num_list = []
with open('filename.txt') as fv:
for row in fv:
num_list.extend(map(int, row.split()))
More efficiently you can use re
import re
with open('filename.txt') as fv:
num_list = list(map(int, re.findall('\d+', fv.read())))
Result (for both above) will be:
[10, 20, 30, 40, 50, 60, 90, 80, 70, 11, 22, 13, 14, 14, 20]
Otherwise in sublists by line/row:
with open('filename.txt') as fv:
num_list = [list(map(int, row.split())) for row in fv]
Result for this:
[[10, 20, 30], [40, 50, 60], [90, 80, 70], [11, 22, 13], [14, 14, 20]]
I think that's what you want to do:
lines = fv.readlines()
num_list = []
for line in lines:
num_list.extend(line.split(' '))
num_list = [int(num.strip()) for num in num_list]
My answer is definitely a longer version but...
text = open('numbers.txt', 'r')
string = text.read()
string = string.replace('\n', ' ')
numbers = string.split(' ')
text.close()
#Print to see the result
print(numbers)
I know the answer is going to be obvious once I see it, but I can't find how to convert my output list of numbers back to letters after I've manipulated the list.
I am putting in data here:
import string
print [ord(char) - 96 for char in raw_input('Write Text: ').lower()]
and I want to be able to reverse this so after I manipulate the list, I can return it back to letters.
example: input gasoline / output [7, 1, 19, 15, 12, 9, 14, 5]
manipulate the output with append or other
then be able to return it back to letters.
Everything I search is only to convert letterst to numbers and nothing to convert that list of numbers back to letters.
Thank you!
It can be done by using chr() built-in function :
my_list = [7, 1, 19, 15, 12, 9, 14, 5]
out = ""
for char in my_list:
out += chr( 96 + char )
print(out) # Prints gasoline
If you want the final output as a list of characters use the first one otherwise the last one.
l = [7, 1, 19, 15, 12, 9, 14, 5] # l is your list of integers
listOfChar = list(map(chr,[x+96 for x in l]))
aWord = "".join(list(map(chr,[x+96 for x in l])))#your word here is "gasoline"
I'm pretty new to python. I'm trying to define a function to read from a given file and count the number of words in each line and output the result as a list.
Here's my code:
def nWs(filename):
with open(filename,'r') as f:
k=[]
for line in f:
num_words=0
words=line.split()
num_words +=len(words)
k.append(num_words)
print (k)
print( nWs('random_file.txt') )
The expected output is something like:
[1, 22, 15, 10, 11, 13, 10, 10, 6, 0]
But it returns:
[1, 22, 15, 10, 11, 13, 10, 10, 6, 0]
None
I don't understand why this term None is returned. There's nothing wrong with the text file, its just random text and I'm only trying to print words in 1 file. So I don't understand this result. Can anyone explain why? And also how can I get rid of this None term.
I assume the indenting is correct when you tried to run it as it wouldn't run otherwise.
The None is the result of you calling the function in the print statement. Because nWs doesn't return anything, the print statement prints None. You could either call the function without the print statement or instead of using print in the function, use return and then print.
def nWs(filename):
with open(filename,'r') as f:
k=[]
for line in f:
num_words=0
words=line.split()
num_words +=len(words)
k.append(num_words)
print (k)
nWs('random_file.txt')
or
def nWs(filename):
with open(filename,'r') as f:
k=[]
for line in f:
num_words=0
words=line.split()
num_words +=len(words)
k.append(num_words)
return k
print(nWs('random_file.txt'))
I have a function called new_safe() and I made a lst with new safe numbers. Now I need to read the sae.txt file with a for loop. Every number that is in safe.txt needs to be deleted from the lst I made.
def nieuwe_kluis():
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
for lijst in lst:
print(lijst)
file = open('kluizen.txt', 'r')
for line in file:
if lst == file:
lst.remove(file)
print(line)
You get the lines from the file, but you use file in the comparison and the remove rather than line.
You also don't check if the line (which I assume is one number per line) is a number within the list. Instead you just try to compare the list itself.
Assuming that each line in the file contains one number, you should try something along the lines of
for line in file:
number = int(line)
if number in lst:
lst.remove(number)
print(line)
I have the following contacts.txt file:
0, 0.989246526088, 0.762584552317, 0.989246526088, 0.989246526088, 5, 2, 20, 91, 114, 127
1, 0.832366089749, 0.67518676348, 0.832366089749, 0.832366089749, 3, 6, 24, 114
2, 0.923079422275, 0.798673866486, 0.923079422275, 0.923079422275, 5, 0, 65, 73, 91, 114
3, 0.0820269441841, 0.879379910489, 0.0820269441841, 0.0820269441841, 3, 71, 91, 120
4, 0.449863833595, 0.985883232333, 0.449863833595, 0.449863833595, 3, 16, 69, 104
6, 0.887055481253, 0.623261413511, 0.887055481253, 0.887055481253, 5, 1, 25, 87, 100, 114
7, 0.111156294437, 0.255444048959, 0.111156294437, 0.111156294437, 3, 19, 83, 111
9, 0.514040361142, 0.373030232483, 0.514040361142, 0.514040361142, 4, 38, 59, 72, 76
11, 0.597169587765, 0.0286747230467, 0.597169587765, 0.597169587765, 3, 56, 101, 108
12, 0.89754811115, 0.361667992685, 0.89754811115, 0.89754811115, 3, 86, 92, 126
13, 0.571528472894, 0.860250953547, 0.571528472894, 0.571528472894, 5, 30, 79, 82, 101, 104
14, 0.593696200969, 0.680733858699, 0.593696200969, 0.593696200969, 3, 78, 103, 124
And so on for 16383 or 16384 lines, depending on the file.
I tried the following code
with open('contacts.dat') as infile:
n, x, y, z, radius, contact_number = [[int(num) for num in line.strip().split()[:5]] for line in infile]
neighbours = [[int(num) for num in line.strip().split()[5:]] for line in infile]
It does not seem to work.
What I am looking for is, for each line of the file, the following storing into different arrays:
PER LINE
zeroth element --> n (where --> means "stored in the array")
first element --> x
second element -- > y
third element --> z
fourth element --> radius
fifth element --> contact_number
remaining elements of the line (if any) --> neighbours
There are a few problems with your list comprehension -- first and foremost, you are creating a list of lists (with some thousand entries) and trying to assign this list to six variables. Better use a loop instead. Also note that you are casting everything to int, while some values are actually floats, but the casting fails anyway because the split line still has commas in it.
Since your file contains comma-separated values, I recommend using the csv module. This will take care of the splitting and comma-stripping stuff. Also, instead of using one large list comprehension, it might be more readable to extract the values individually, or in groups.
import csv
with open("contacts.dat") as infile:
for line in csv.reader(infile):
num = int(line[0])
x, y, z, radius = map(float, line[1:5])
contact = int(line[5])
neighbors = map(int, line[6:])
Now that the individual values are extracted, all that's left to do is to store them in some data structure, e.g., a list of dictionaries, names tuples, or some special class.
You're trying to store the columns of your input, but unpacking gives the rows. Transpose it first:
def transpose(grid):
return zip(*grid)
Alternative method: NumPy
import numpy as np
nparray = np.genfromtxt('contacts.txt',delimiter = ',')
#Where column N is accessed by nparray[:,n]
another approach to reading the file using only built-in functions..
def atonum(x):
if x.find('.') < 0: return int(x)
return float(x)
with open(filename) as infile:
alldata=[[ atonum(y) for y in x.strip().split(',') ] for x in infile]