I want a pattern like:
Input : Python is Interactive (any string separated by space)
Expected Output:
*************
*Python *
*is *
*Interactive*
*************
I tried using python's "re" module ,not able to create the stars in the pattern
inp = "Python is interactive"
import re
split = re.split(' ', inp)
length = []
for item in range(len(split)):
length.append(len(split[item]))
Max = (max(length))
for i in range(len(split)):
print(split[i])
You don't need the re module. Your approach is not that bad, but needs some rework:
input = "Python is interactive"
parts = input.split(" ")
maxlen = max(map(lambda part: len(part), parts))
# or this, if you want to go even more elegant:
maxlen = max(map(len, parts))
print ('*' * (maxlen + 4))
for part in parts:
spaces = maxlen - len(part)
print("* " + part + (" " * spaces) + " *")
print ('*' * (maxlen + 4))
For splitting you can use the string.split method. Then I calculate the maximum length (like you did, but a little bit more elegant).
Then I print as many stars as the most long string is + 4 because at the beginning and end of each string there is "* " and " *", so 4 more characters.
Then I print the string with as many spaces as padding as needed.
Finally the last line of stars.
i am new to Python and i cant get this.I have a List and i want to take the input from there and write those in files .
p = ['Eth1/1', 'Eth1/5','Eth2/1', 'Eth2/4','Eth101/1/1', 'Eth101/1/2', 'Eth101/1/3','Eth102/1/1', 'Eth102/1/2', 'Eth102/1/3','Eth103/1/1', 'Eth103/1/2', 'Eth103/1/3','Eth103/1/4','Eth104/1/1', 'Eth104/1/2', 'Eth104/1/3','Eth104/1/4']
What i am trying :
with open("abc1.txt", "w+") as fw1, open("abc2.txt", "w+") as fw2:
for i in p:
if len(i.partition("/")[0]) == 4:
fw1.write('int ' + i + '\n mode\n')
else:
i = 0
while i < len(p):
start = p[i].split('/')
if (start[0] == 'Eth101'):
i += 3
key = start[0]
i += 1
while i < len(p) and p[i].split('/')[0] == key:
i += 1
end = p[i-1].split('/')
fw2.write('confi ' + start[0] + '/' + start[1] + '-' + end[1] + '\n mode\n')
What i am looking for :
abc1.txt should have
int Eth1/1
mode
int Eth1/5
mode
int Eth2/1
mode
int Eth 2/4
mode
abc2.txt should have :
int Eth101/1/1-3
mode
int Eth102/1/1-3
mode
int Eth103/1/1-4
mode
int Eth104/1/1-4
mode
So any Eth having 1 digit before " / " ( e:g Eth1/1 or Eth2/2
)should be in one file that is abc1.txt .
Any Eth having 3 digit before " / " ( e:g Eth101/1/1 or Eth 102/1/1
) should be in another file that is abc2.txt and .As these are in
ranges , need to write it like Eth101/1/1-3, Eth102/1/1-3 etc
Any Idea ?
I don't think you need a regex here, at all. All your items begin with 'Eth' followed by one or more digits. So you can check the length of the items before first / occurs and then write it to a file.
p = ['Eth1/1', 'Eth1/5','Eth2/1', 'Eth2/4','Eth101/1/1', 'Eth101/1/2', 'Eth101/1/3','Eth102/1/1', 'Eth102/1/2', 'Eth102/1/3','Eth103/1/1', 'Eth103/1/2', 'Eth103/1/3','Eth103/1/4','Eth104/1/1', 'Eth104/1/2', 'Eth104/1/3','Eth104/1/4']
with open("abc1.txt", "w+") as fw1, open("abc2.txt", "w+") as fw2:
for i in p:
if len(i.partition("/")[0]) == 4:
fw1.write('int ' + i + '\n mode\n')
else:
fw2.write('int ' + i + '\n mode\n')
I refactored your code a little to bring with-statement into play. This will handle correctly closing the file at the end. Also it is not necessary to iterate twice over the sequence, so it's all done in one iteration.
If the data is not as clean as provided, then you maybe want to use regexes. Independent of the regex itself, by writing if re.match(r'((Eth\d{1}\/\d{1,2})', "p" ) you proof if a match object can be created for given regex on the string "p", not the value of the variable p. This is because you used " around p.
So this should work for your example. If you really need a regex, this will turn your problem in finding a good regex to match your needs without any other issues.
As these are in ranges , need to write it like Eth101/1/1-3, Eth102/1/1-3 etc
This is something you can achieve by first computing the string and then write it in the file. But this is more like a separate question.
UPDATE
It's not that trivial to compute the right network ranges. Here I can present you one approach which doesn't change my code but adds some functionality. The trick here is to get groups of connected networks which aren't interrupted by their numbers. For that I've copied consecutive_groups. You can also do a pip install more-itertools of course to get that functionality. And also I transformed the list to a dict to prepare the magic and then retransformed dict to list again. There are definitely better ways of doing it, but this worked for your input data, at least.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from itertools import groupby
from operator import itemgetter
p = ['Eth1/1', 'Eth1/5', 'Eth2/1', 'Eth2/4', 'Eth101/1/1', 'Eth101/1/2',
'Eth101/1/3', 'Eth102/1/1', 'Eth102/1/2', 'Eth102/1/3', 'Eth103/1/1',
'Eth103/1/2', 'Eth103/1/3', 'Eth103/1/4', 'Eth104/1/1', 'Eth104/1/2',
'Eth104/1/3', 'Eth104/1/4']
def get_network_ranges(networks):
network_ranges = {}
result = []
for network in networks:
parts = network.rpartition("/")
network_ranges.setdefault(parts[0], []).append(int(parts[2]))
for network, ranges in network_ranges.items():
ranges.sort()
for group in consecutive_groups(ranges):
group = list(group)
if len(group) == 1:
result.append(network + "/" + str(group[0]))
else:
result.append(network + "/" + str(group[0]) + "-" +
str(group[-1]))
result.sort() # to get ordered results
return result
def consecutive_groups(iterable, ordering=lambda x: x):
"""taken from more-itertools (latest)"""
for k, g in groupby(
enumerate(iterable), key=lambda x: x[0] - ordering(x[1])
):
yield map(itemgetter(1), g)
# only one line added to do the magic
with open("abc1.txt", "w+") as fw1, open("abc2.txt", "w+") as fw2:
p = get_network_ranges(p)
for i in p:
if len(i.partition("/")[0]) == 4:
fw1.write('int ' + i + '\n mode\n')
else:
fw2.write('int ' + i + '\n mode\n')
I have set of coordinates that are randomly separated with an empty line:
19.815857300 39.791813400
19.816105700 39.791921800
19.816220800 39.791984600
19.816271400 39.792010000
19.786375895 39.678097997
19.783813875 39.677022719
19.782758486 39.676590122
and so on...lot of coordinates :)
I want to insert a specific text at the beginning and at the end of the 1st coordinates set,( first line of the "paragraph").
The same for the last line of each paragraph - different text entry
The coordinates between them, also need another text before and after.
so.. the result I would like to achieve, should be something like
BEGIN_SEGMENT 0 50 10 19.815857300 39.791813400 0.00000000
SHAPE_POINT 19.816105700 39.791921800 0
SHAPE_POINT 19.816220800 39.791984600 0
END_SEGMENT 20 19.816271400 39.792010000 0.00000000
BEGIN_SEGMENT 0 50 10 19.786375895 39.678097997 0.00000000
SHAPE_POINT 19.783813875 39.677022719 0
END_SEGMENT 20 19.782758486 39.676590122 0.00000000
etc..etc..
Any ideas on how this could be done with notepad++ and regular expressions?
Thanx in advance!
Solution using python 3.6.
It reads in a file "input.txt" - line by line - until it gets an empty line.
On each start it recreates the file "result.txt".
Each found paragraph is appended to "result.txt" - until done.
Now you just need to get a python environment ;o) and feed it your file.
import re
import datetime
import random
# recreate empty file with timestamp
with open("result.txt","w") as r:
r.write(str(datetime.datetime.now()) + "\n")
with open("input.txt","r") as f:
while True:
paragraph = []
line = f.readline()
if line == "":
break # readline always retunrs \n on empty lines until file end reached
while len(line.strip()) > 0:
# accumulate lines
paragraph.append(line.strip())
line = f.readline()
if not paragraph:
continue # jumps back up to while True:
rv = []
for idx in range(0,len(paragraph)):
if idx == 0:
rv.append("BEGIN_SEGMENT 0 50 " + str(random.randint(1,10000)) + " " + paragraph[idx] + " 0.00000000 " + "\n")
elif idx != (len(paragraph) - 1):
rv.append("SHAPE_POINT " + paragraph[idx] + " 0" + "\n")
else:
rv.append("END_SEGMENT " + str(random.randint(1,10000)) + " " + paragraph[idx] + " 0.00000000" + "\n" + "\n")
# append results of paragraph
with open("result.txt","a") as resFile:
for line in rv:
resFile.write(line)
# edited code for random numbers instead of fixed ones
Not complete - you'll have to adjust the first and last rows by hand.
Step 1 end segment-begin segment
FIND:\r\n(\d.*)\r\n\r\n
REPLACE: \r\nEND_SEGMENT\t$1\r\n\r\nBEGIN_SEGMENT\t
Step 2: shape point
FIND: ^(\d.*)$
REPLACE: SHAPE_POINT\t$1
Assumes that there will be only one blank line between segments.
You can use https://regexper.com/ to display a diagram of the expressions.
lines = [[str(i * j) for i in xrange(1, 13)] for j in xrange(1, 13)]
for line in lines:
for num in line:
if line.index(num):
print ' ' * (3 - len(num)) + num,
else:
print ' ' * (2 - len(num)) + num,
print
I am trying to understand why the else statement pertains to the first line
and the line.index(num) pertains to remaining lines.
As your if statement is not comparing the return of line.index(num) against anything, returning any non zero value will satisfy the condition and returning a value of 0 will result in the else statement.
line.index(num) returns 0 if num is the first entry in line and so only acts on the first entry from each line in lines.
I've been trying to make this work for some time now and I can't seem to get my list to sort out in ascending order. My program asks the user to enter three integers and then outputs results and is supposed to sort the numbers entered from least to greatest. However, whenever I try to sort it, it does not sort it the way I want to do. I've tried several ways of modifying the sort method, but it still does not work. For example, if I enter in 2, 10, and 5 as my three numbers, it will display it as "List: [2, 10, 5]".
import math
print ("")
print ("Welcome to my program!")
print ("")
v1 = input("Enter the first number: ")
print ("")
v2 = input("Enter the second number: ")
print ("")
v3 = input("Enter the third number: ")
print ("")
#tried to sort list here
list1 = [int(v1), int(v2), int(v3)]
sorted(list1, key=int)
sum = int(v1) + int(v2) + int(v3)
product = int(v1) * int(v2) * int(v3)
integer = int(v1)//int(v2)
mod = float(v1) % float(v2)
average = (float(v1) + float(v2) + float(v3))/ 3
star= "*"
print ("------------------")
print (" RESULTS ")
print ("------------------")
print ("")
print ("Sum: " + str(sum))
print ("")
print ("Product: " + str(product))
print ("")
print ("Integer Division: "+ str(integer))
print ("")
print ("Mod: " + str(mod))
print ("")
print ("Maximum Number: ", max(list1))
print ("")
print ("Minimum Number: ", min(list1))
print ("")
print ("Average: " + str(average))
print ("")
#outputs the list
print ("List: " + str(list1))
print ("")
print (v1 + " " + "".join([star] * int(v1)))
print (v2 + " " + "".join([star] * int(v2)))
print (v3 + " " + "".join([star] * int(v3)))
You need to assign to the sorted output:
srted = sorted(list1) # creates a new list
To sort the original list sorting in place use list.sort:
list1.sort() # sorts original list
You don't need to pass a key to sort ints.
sorted returns a value that you must reassign and the key is unnecessary:
list1 = [int(v1), int(v2), int(v3)]
list1 = sorted(list1)
Alternatively, you can call the sort method of the list which directly modifies it without return and reassignment:
list1 = [int(v1), int(v2), int(v3)]
list1.sort()