I am trying to read a file that looks like this:
83 124 125
83 125 126
83 126 127
83 127 128
83 128 128
154 120 120
154 120 121
154 121 122
154 122 123
154 123 124
122 92 93
122 93 94
122 94 95
122 95 96
122 96 97
And write to different files every set of values. The first value (83 / 154 / 122) needs to be the text file's name. The rest of the values should be written into their correspondent file like so: 124 128
So file "83.txt" contains 124 128. The file "154.txt" contains 120 124. And the file "122.txt should contain 92 97.
How do i iterate over the above mentioned input and remove duplicate values from the first column? Then proceed into taking the minimum and maximum values that each of the first values share? and finally write each separate line into a new text file inside a certain folder?
I have tried to use:
from itertools import chain
from collections import defaultdict
from operator import itemgetter
from itertools import groupby
def final(f):
with open (f+'.txt', 'r') as fin:
lines = fin.readlines().split().strip('\n')
v1, v2, v3 = lines[0], lines[1], lines[2]
for v1, g in groupby(enumerate(diffs[v1x]), lambda (i, x): i - x):
group = map(itemgetter(1), g)
lines.itertools.chain()
lines = defaultdict(list)
print (lines),
Which is an incomplete version of what i had earlier but i can't seem to make it work like it did before. Anyway my code ended up very long and not that readable... If more details are required for this to be answered I'll provide them. I'd like to see different takes on this and not simply posting my crude code and get it tweaked by someone.
Assuming the filenames are "in order", and the other items are in order, then:
from itertools import groupby
from operator import itemgetter
from collections import deque
with open('/home/jon/testdata.txt') as fin:
lines = (line.split() for line in fin)
for k, g in groupby(lines, itemgetter(0)):
fst = next(g)
lst = next(iter(deque(g, 1)), fst)
with open(k + '.txt', 'w') as fout:
fout.write(fst[1] + ' ' + lst[2])
long_string = """ 83 124 125
83 125 126
83 126 127
83 127 128
83 128 128
154 120 120
154 120 121
154 121 122
154 122 123
154 123 124
122 92 93
122 93 94
122 94 95
122 95 96
122 96 97
"""
files = {}
for line in long_string.split("\n"):
try:
filenum, minvalue, maxvalue = line.strip().split(" ")
try:
new_min = min(files[filenum][0], minvalue)
new_max = max(files[filenum][1], maxvalue)
files[filenum] = (new_min, new_max)
except KeyError:
files[filenum] = (minvalue, maxvalue)
except ValueError:
print("There are no 3 values as excpected")
for filename, values in files.iteritems():
with open(filename + ".txt", "wb") as writer:
writer.write(values[0] + " " + values[1])
Related
I am looking for a plugin that can encrypt/decrypt text using rot18 in Sublime Text v3.2.2.
I tried this tutorial (only rot13) but it doesn’t work for me: https://www.sublimetext.com/docs/plugin-examples
I tried a lot of plugins and the only one that works fine is:
(unfortunately it is rot47)
import sublime
import sublime_plugin
class Rot47Command(sublime_plugin.TextCommand):
def run(self, edit):
for region in self.view.sel():
if not region.empty():
s = self.view.substr(region)
s = ''.join(chr(33 + ((ord(ch) + 14) % 94)) for ch in s)
self.view.replace(edit, region, s)
Does anyone have any functional plugin on rot18, please?
You can adapt your code. Here is how rot_N works:
This is the ASCII-Range up to 127:
a = 32
for k in range(0,16):
print(a+k, chr(a+k), " ", a+16+k, chr(a+16+k), " ", a+32+k, chr(a+32+k), " ",
a+48+k, chr(a+48+k), " ", a+64+k, chr(a+64+k), " ", a+80+k, chr(a+80+k))
# 32 48 0 64 # 80 P 96 ` 112 p
# 33 ! 49 1 65 A 81 Q 97 a 113 q
# 34 " 50 2 66 B 82 R 98 b 114 r
# 35 # 51 3 67 C 83 S 99 c 115 s
# 36 $ 52 4 68 D 84 T 100 d 116 t
# 37 % 53 5 69 E 85 U 101 e 117 u
# 38 & 54 6 70 F 86 V 102 f 118 v
# 39 ' 55 7 71 G 87 W 103 g 119 w
# 40 ( 56 8 72 H 88 X 104 h 120 x
# 41 ) 57 9 73 I 89 Y 105 i 121 y
# 42 * 58 : 74 J 90 Z 106 j 122 z
# 43 + 59 ; 75 K 91 [ 107 k 123 {
# 44 , 60 < 76 L 92 \ 108 l 124 |
# 45 - 61 = 77 M 93 ] 109 m 125 }
# 46 . 62 > 78 N 94 ^ 110 n 126 ~
# 47 / 63 ? 79 O 95 _ 111 o 127
ROT n means you take the chr(ord(l)+n)'s letter instead. You need to be carefull when wrapping around.
For calculation of rot_N the basic formular is:
def rot_N(n,letter):
return chr( (ord(letter)-32+n) % (128-32) + 32) # 128-32 = 96
You can test it with:
k="Hello Zzzzz"
print( ''.join(rot_N(18, l) for l in k)) # schould give you a tranlation
print( ''.join(rot_N(0, l) for l in k)) # should give the exact text
and test the inverse with:
k_inverse ="Zw~~!2l,,,,"
print( ''.join(rot_N(-18, l) for l in k_inverse)) # use -18 here
print( ''.join(rot_N(0, l) for l in k_inverse))
If you replace
s = ''.join(chr(33 + ((ord(ch) + 14) % 94)) for ch in s)
with
s = ''.join(rot_N(18, ch) for ch in s))
you should be fine.
You do not specify, but I assume you are using ROT-18 on the character set 0..9, A..Z which is 36 characters. 36/2 = 18, hence ROT-18.
ROT-13 works on the 26 alphabetic characters: 26/2 = 13. You want to adapt that to ROT-18.
The major difference is that the alphabetic characters are continuous in the ASCII character set, and that assumption is built into the code you are copying from. The same is true for ROT-47; the ASCII characters used are continuous. With ROT-18, the digits 0..9 and the alphabetic characters, A..Z are not continuous in ASCII. There is a gap between them from : (#58) to # (#64). ASCII codes in that region are neither digits nor letters.
One solution is to set up your own array, not in the ASCII order, where the two are continuous: [0, 1, ... 9, A, B, ... Z]. Write your program to work on that array.
Alternatively you can work with the ASCII codes, treating codes from #58 to #64 specially to make the shift come out right.
The first option is probably easier, and the code will be more similar to the ROT-13 example. The main difference will be replacing the ord() function, which returns the ASCII code, with an equivalent function giving the position in your array.
I am new in Python and i have a question. I have an exported .csv with values and i want to sum each row's total value than make a total column to there.
I've tried that but it doesnt work.
import pandas as pd
wine = pd.read_csv('testelek.csv', 'rb', delimiter=';')
wine['Total'] = [wine[row].sum(axis=1) for row in wine]
I want to make my DataFrame like this.
101 102 103 104 .... Total
__________________________________________________________________________
0 80 84 86 78 .... 328
1 78 76 77 79 .... 310
2 79 81 88 83 .... 331
3 70 85 89 84 .... 328
4 78 84 88 85 .... 335
You can bypass the need for the list comprehension and just use the axis=1 parameter to get what you want.
wine['Total'] = wine.sum(axis=1)
A nice way to do this is by using .apply().
Suppose that you want to create a new column named Total by adding the values per row for columns named 101, 102, and 103 you can try the following:
wine['Total'] = wine.apply(lambda row: sum([row['101'], row['102'], row['103']]), axis=1)
I need to change the names of a subset of columns in a dataframe from whatever number they are to that number plus a string suffix. I know there is a function to add a suffix, but it doesn't seem to work on just indices.
I create a list with all the column indices in it, then run a loop that, for each item in that list, it renames the dataframe column that matches the list item to the same number, plus the suffix string.
if scalename == "CDR":
print(scaledf.columns.tolist())
oldCols = scaledf.columns[7:].tolist()
for f in range(len(oldCols)):
changeCol = int(oldCols[f])
print(changeCol)
scaledf.rename(columns = {changeCol:scalename + str(changeCol)})
print(scaledf.columns)
This doesn't work.
The code will print out the column names, and prints out every item, but it does not rename the columns. It doesn't throw errors, it just doesn't work. I've tried variation after variation, and gotten all kinds of other errors, but this error-free code does nothing. It just runs, and doesn't rename anything.
Any help would be seriously appreciated! Thank you.
Adding sample of list:
45
52
54
55
59
60
61
66
67
68
69
73
74
75
80
81
82
94
101
103
104
108
110
115
116
117
129
136
138
139
143
144
145
150
151
157
158
159
171
178
180
181
185
186
187
192
193
199
200
201
213
220
222
223
227
228
229
234
235
236
Try this:
scaledf = scaledf.rename(columns=lambda c:scalename + str(c) if c in oldCols else c)
import csv
import output
fill = input("Enter File name:")
f = open(fill)
csv_f = csv.reader(f)
m = open('data.csv', "w")
dict_out = {}
for row in csv_f:
if row[1] in dict_out:
dict_out[row[1]] += row[3]
else:
dict_out[row[1]] = row[3]
for title, value in dict_out.items():
m.write('{},'.format(title))
m.write ('{} \n'.format(value))
m.close()
Prints my csv as
Title,Detail
Siding, 50 63 22 68 138 47 123 107 107 93 117
Asphalt, 49 8 72 19 125 95 33 83 123 144
Rail, 82 98 89 62 58 66 24 77 120 93
Grinding, 127 47 20 66 29 137 33 145 3 98
Concrete, 130 75 12 88 22 137 114 88 143 16
I would like to put a comma in between the numbers. I have tried m.write(',') after m.write('{} \n'.format(value)) but it only adds it after the last one. How can i format it so it will output as
Title,Detail
Siding, 50,63,22,68,138,47,123,107,107,93,117
Asphalt, 49,8,72,191,25,95,33,83,123,144
Rail, 82,98,89,62,58,66,24,77,120,93
Grinding, 127,47,20,66,29,137,33,145,3,98
Concrete, 130,75,12,88,22,137,114,88,143,16
not the best way but you can:
for title, value in dict_out.items():
m.write('{},'.format(title))
m.write ('{} \n'.format(value.replace(' ', ',')))
but you should definetly use csv writter,
import csv
import output
fill = input("Enter File name:")
f = open(fill)
csv_f = csv.reader(f)
c = open('data.csv', "w")
m = csv.writer(c)
dict_out = {}
for row in csv_f:
if row[1] in dict_out:
dict_out[row[1]].append(row[3])
else:
dict_out[row[1]] = [row[3]]
for title, value in dict_out.items():
m.writerow([title] + value)
c.close()
If value is a string then you need to use value.split(). If it is already a list then you don't need to use the split method.
with open('data.csv', "w") as m:
for title, value in dict_out.items():
m.write(title + "," + ",".join(value.split()) + "\n")
88 90 94 98 100 110 120
75 77 80 86 94 103 113
80 83 85 94 111 111 121
68 71 76 85 96 122 125
77 84 91 102 105 112 119
81 85 90 96 102 109 134
Hi i am very new to computer programming in general and I need some help with my current project. I need to read numbers from a text file into a table and calculate the averages and max.This is what I currently have.
def main():
intro()
#sets variables
n1=[]
n2=[]
n3=[]
n4=[]
n5=[]
n6=[]
n7=[]
numlines = 0
filename = input("Enter the name of the data file: ")
print() #turnin
infile = open(filename,"r")
for line in infile:
#splits the lines
data = line.split()
#takes vertical lines individually and converts them to integers
n1.append(int(data[0]))
n2.append(int(data[1]))
n3.append(int(data[2]))
n4.append(int(data[3]))
n5.append(int(data[4]))
n6.append(int(data[5]))
n7.append(int(data[6]))
datalist = n1,n2,n3,n4,n5,n6
#calculates the average speeds
n1av = (sum(n1))/len(n1)
n2av = (sum(n2))/len(n2)
n3av = (sum(n3))/len(n3)
n4av = (sum(n4))/len(n4)
n5av = (sum(n5))/len(n5)
n6av = (sum(n6))/len(n6)
n7av = (sum(n7))/len(n7)
#calculates the max speeds
n1max = max(n1)
n2max = max(n2)
n3max = max(n3)
n4max = max(n4)
n5max = max(n5)
n6max = max(n6)
n7max = max(n7)
#Calculates the average of the average speeds
Avgav = (n1av + n2av + n3av + n4av + n5av + n6av + n7av) / 7
#Calculates the average of the average max
Avmax = (n1max + n2max + n3max + n4max + n5max + n6max + n7max) / 7
#creates table
print(aver_speed)
print()
print(" "* 27, "Speed (MPH)")
print(" "*3,"Car :", "{:6}".format(30),"{:6}".format(40),"{:6}".format(50)
,"{:6}".format(60),"{:6}".format(70),"{:6}".format(80),
"{:6}".format(90)," :","{:14}".format ("Average Noise"))
print("-"*77)
for i in range(0,len(datalist)):
print("{:6}".format(int("1")+1)," "*2,":", "{:6}".format (n1[i]), "{:6}".format (n2[i]), "{:6}".format (n3[i]),
"{:6}".format (n4[i]),"{:6}".format (n5[i]),"{:6}".format (n6[i]),"{:6}".format (n7[i])," :", )
print("-"*77)
print(" ","Average","{:1}".format(":"), "{:8.1f}".format(n1av),"{:6.1f}".format(n2av),
"{:6.1f}".format(n3av),"{:6.1f}".format(n4av),"{:6.1f}".format(n5av),"{:6.1f}".format(n6av),
"{:6.1f}".format(n7av), "{:9.1f}".format(Avgav))
print()
print(" ","Maximum","{:1}".format(":"), "{:6}".format(n1max), "{:6}".format(n2max), "{:6}".format(n3max), "{:6}".format(n4max)
, "{:6}".format(n5max), "{:6}".format(n6max), "{:6}".format(n7max),"{:11.1f}".format(Avmax))
Any help would be appreciated.
Now that i have updated my code my table looks like this:
Car : 30 40 50 60 70 80 90 : Average Noise
2 : 88 90 94 98 100 110 120 :
2 : 75 77 80 86 94 103 113 :
2 : 80 83 85 94 111 111 121 :
2 : 68 71 76 85 96 122 125 :
2 : 77 84 91 102 105 112 119 :
2 : 81 85 90 96 102 109 134 :
Average : 78.2 81.7 86.0 93.5 101.3 111.2 122.0 96.3
Maximum : 88 90 94 102 111 122 134 105.9
I've been trying to figure out the calculations for average noise and how to list the cars 1 through 6. I was unable to fi
You have a lot of code now. You can do this easier. If you want calculate by strings:
with open(filename, 'r') as f:
for line in f.readlines():
list_of_speed = map(int, line.split())
max_speed = max(list_of_speed)
aver_speed = float(sum(list_of_speed))/len(list_of_speed)
If by column:
with open(filename, 'r') as f:
l = map(lambda x: map(int, x.split()), f.readlines())
for n in range(len(l[0])):
list_of_speed = [value[n] for value in l]
max_speed = max(list_of_speed)
aver_speed = float(sum(list_of_speed))/len(list_of_speed)
You can use sum() function on a list and len() function gives the number of elements in the list. So for average calculation you can simply do sum(n1)/float(len(n1)).
Try to use some dynamic way of keeping track of read data or calculate sum and avg on the fly and keep track of that data. Not to discourage you but using six lists doesn't look so elegant. Hope something similar to this might work:
from pprint import pprint
def main():
# intro()
filename = input("Enter the name of the data file:")
infile = open(filename,"r")
n = {} # a dictionary
for line in infile:
# apply typecasting on each element
data = map(int, line.split())
# add speeds into to a dictionary of lists
# supports any number of data sets
for i,d in enumerate(data):
if i+1 in n:
n[i+1].append(d)
else:
n[i+1] = [d]
pprint (n)
# do whatever you want with the dictionary
for d in n:
print ("-" * 10)
print (d)
print (sum(n[d]))
print (sum(n[d])/float(len(n[d])))
main()
For printing purposes you may want to use some thing like https://pypi.python.org/pypi/PTable