def selectionSort(lst):
with lst as f:
nums = [int(line) for line in f]
for i in range(len(nums) - 1, 0, -1):
maxPos = 0
for position in range(1, i + 1):
if nums[position] > nums[maxPos]:
maxPos = position
value = nums[i]
nums[i] = nums[maxPos]
nums[maxPos] = value
def main():
textFileName = input("Enter the Filename: ")
lst = open(textFileName)
selectionSort(lst)
print(lst)
main()
Okay, thanks to hcwhsa for helping me out with the reading file and putting them all in one line.
When I run that code, i get this following error:
<_io.TextIOWrapper name='numbers.txt' mode='r' encoding='UTF-8'>
textfile:
67
7
2
34
42
Any help? Thanks.
You should return the list from the function and assign it to a variable and then print it.
def selectionSort(lst):
with lst as f:
nums = [int(line) for line in f]
...
...
return nums
sorted_lst = selectionSort(lst)
print(sorted_lst)
Your code didn't work because instead of passing the list you passed the file object to the function. This version of your code passes the list to the function, so no return value is required as you're modifying the same list object:
def selectionSort(nums):
for i in range(len(nums) - 1, 0, -1):
maxPos = 0
for position in range(1, i + 1):
if nums[position] > nums[maxPos]:
maxPos = position
value = nums[i]
nums[i] = nums[maxPos]
nums[maxPos] = value
def main():
textFileName = input("Enter the Filename: ")
with open(textFileName) as f:
lst = [int(line) for line in f]
selectionSort(lst)
print(lst)
main()
Related
I want to save the loop result into a csv file or dataframe; the below code just writes the tweets to the console.
j =1
sortedDF = tweets_df.sort_values(by = ['Polarity'])
for i in range (0, sortedDF.shape[0]):
if(sortedDF['Analysis'][i] == 'Positive'):
print(str(j)+')'+ sortedDF['transalted'][i])
print()
j = j+1
with open("some.csv", "w") as f:
j = 1
sortedDF = tweets_df.sort_values(by=['Polarity'])
for i in range(0, sortedDF.shape[0]):
if (sortedDF['Analysis'][i] == 'Positive'):
f.write(str(j) + ')' + sortedDF['transalted'][i])
print()
j = j + 1
We can call writelines at the end instead of write in for loop which is more optimized solution.
sortedDF = tweets_df.sort_values(by=['Polarity'])
file = open("positive_tweets.csv", "w")
lines = []
j = 1
for i in range(0, sortedDF.shape[0]):
if (sortedDF['Analysis'][i] == 'Positive'):
lines.append(str(j) + ')' + sortedDF['transalted'][i])
j += 1
file.writelines(lines)
file.close()
When I input 7,17 but the result is
ifDescr.7
ifDescr.70
ifDescr.17
If I want the result is 7 and 17 when I input 7 17, how do I code it?
ifDescr.7
ifDescr.17
text file
ifDescr.7
ifDescr.70
ifDescr.17
def search_multiple(file_name, list_of_strings):
line_number = 0
list_of_results = []
with open(file_name, 'r') as read:
for line in read:
line_number += 1
for x in list_of_strings:
if x in line:
list_of_results.append((x,line_number,line.rstrip()))
return list_of_results
def main ():
folder = ('single.txt')
verify1,verify2 = input ("Input number").split()
matched_lines = search_multiple(folder,['ifDescr.' + verify1, 'ifDescr.' + verify2,])
for x in matched_lines:
print('Line = ', x[2])
if __name__ == '__main__':
main()
The reason for this behavior is you are using in to check if string is in the line. As ifDescr.70 contains ifDecsr.7 in it,the result contains it as well. Try out the below function:
def search_multiple(file_name, list_of_strings):
line_number = 0
list_of_results = []
with open(file_name, 'r') as read:
for line in read:
line_number += 1
for x in list_of_strings:
if x == line.strip():
list_of_results.append((x,line_number,line.rstrip()))
return list_of_results
I have a text file of format like this
10:45 a b c
x 0 1 2
y 4 5 6
z 7 8 9
I want to make x as key and 0,1,2 its value in the list.Same with y and z
while(1):
line = f.readline()
if time in line:
print (line)
L1.append(line)
for count,line in enumerate(f):
if (i < 3):
L1.append(line)
print ("Line{} : {}".format(count,line.strip()))
i=i+1
#print(L1)
for k in range(1):
print(L1[k])
test1 = L1[k]
a1 = test1.split()
print (a1[1])
dict = {a1[1]: L1[k] for a1[1] in L1[k]}
print (dict)
for k in range(1,3):
#print("hey")
print (L1[k]) #will list the single row
test = L1[k]
#print(test)
a = test.split()
print (a[0])
dict = {a[0]:L1[k] for a[0] in L1[k]}
print (dict)
Any idea what i am doing wrong here?
P.S. - I am new to python
You could try this:
my_dict = {}
lines = f.readLines()
lines.pop(0)
for line in lines:
line_list = line.split(' ')
key = line_list.pop(0)
my_dict.update({key: line_list})
This will accomplish what it is I think you need (assuming your text file is stored in the same directory and you replace 'test.txt' with your filename):
with open('test.txt', 'r') as values:
contents = values.read().strip().split()
new_dict = {}
i = 4
while i <= len(contents)-4:
new_dict.update({contents[i]: contents[i+1:i+4]})
i += 4
print(new_dict)
or this, if you want the values as integers:
with open('test.txt', 'r') as values:
contents = values.read().strip().split()
new_dict = {}
i = 4
while i <= len(contents)-4:
new_dict.update({contents[i]: [int(contents[i+1]),int(contents[i+2]),int(contents[i+3])]})
i += 4
print(new_dict)
Try this
import string
start_found = False
result_dict = {}
for line in open("stack1_input.txt", mode='r'):
if (line.startswith("10:45")):
start_found = True
continue
if start_found == True:
values = line.split()
if len(values) == 4:
result_dict[values[0]] = values[1:]
print (result_dict)
I keep getting the error when running my code:
TypeError: object of type '_io.TextIOWrapper' has no len() function
How do I get it to open/read the file and run it through the loop?
Here's a link to the file that I am trying to import:
download link of the DNA sequence
def mostCommonSubstring():
dna = open("dna.txt", "r")
mink = 4
maxk = 9
count = 0
check = 0
answer = ""
k = mink
while k <= maxk:
for i in range(len(dna)-k+1):
sub = dna[i:i+k]
count = 0
for i in range(len(dna)-k+1):
if dna[i:i+k] == sub:
count = count + 1
if count >= check:
answer = sub
check = count
k=k+1
print(answer)
print(check)
The problem occurs due to the way you are opening the text file.
You should add dna = dna.read() to your code.
so your end code should look something like this:
def mostCommonSubstring():
dna = open("dna.txt", "r")
dna = dna.read()
mink = 4
maxk = 9
count = 0
check = 0
answer = ""
k = mink
while k <= maxk:
for i in range(len(dna)-k+1):
sub = dna[i:i+k]
count = 0
for i in range(len(dna)-k+1):
if dna[i:i+k] == sub:
count = count + 1
if count >= check:
answer = sub
check = count
k=k+1
print(answer)
print(check)
#tfabiant : I suggest this script to read and process a DNA sequence.
To run this code, in the terminal: python readfasta.py fastafile.fasta
import string, sys
##########I. To Load Fasta File##############
file = open(sys.argv[1])
rfile = file.readline()
seqs = {}
##########II. To Make fasta dictionary####
tnv = ""#temporal name value
while rfile != "":
if ">" in rfile:
tnv = string.strip(rfile)
seqs[tnv] = ""
else:
seqs[tnv] += string.strip(rfile)
rfile = file.readline()
##############III. To Make Counts########
count_what = ["A", "T", "C", "G", "ATG"]
for s in seqs:
name = s
seq = seqs[s]
print s # to print seq name if you have a multifasta file
for cw in count_what:
print cw, seq.count(cw)# to print counts by seq
This is a magic square program that can find out if any size matrix is a magic square. When i run the code i get error TypeError: 'int' object is not subscriptable. I decided to change line = int(i) to line = i but that just gave me another error. Cant use numpy
EDIT: Now i get this error TypeError: 'int' object is not iterable
text file:
1 1
6 8
Here is code:
def main():
filNam = "matrix8.txt"
matrix = (readMatrix(filNam))
rowNum = 0
colNum = 0
print(rowSum(matrix, rowNum))
def readMatrix(filNam):
matrixList = []
numFile = open(filNam, "r")
lines = numFile.readlines()
for line in lines:
line = line.split()
row = []
for i in line:
row.append(int(i))
matrixList.append(row)
return matrixList
def eachNumPresent(matrix):
if len(matrix) % 2 != 0:
return False
else:
return True
def rowSum(matrix, rowNum):
for row in matrix[rowNum]:
row = sum(int(row))
rowNum = rowNum + 1
return i
def colSum(matrix):
length = len(matrix)
col_rows = 0
for i in range(length):
col_rows = col_rows + matrix[i][0]
return col_rows
main()
The problem is that the matrix gets "flatten" into one long row. In order to fix it you should read & construct the matrix row-by-row.
Change:
def readMatrix(filNam):
matrixList = []
numFile = open(filNam, "r")
lines = numFile.readlines()
for line in lines:
line = line.split()
for i in line:
line = int(i)
matrixList.append(line)
return matrixList
to:
def readMatrix(filNam):
matrixList = []
numFile = open(filNam, "r")
lines = numFile.readlines()
for line in lines:
line = line.split()
row = [] # 1st change
for i in line:
row.append(int(i)) # 2nd change
matrixList.append(row) #3rd change
return matrixList
changing the code and running it on the input provided in the question it prints 2 which is the sum of the first row in the matrix.